with asp.net core and ef core when i try to seed there went wrong - asp.net-core

My startup.cs is
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
SeedData.Seed(app);
}
and my seed class is :
public static class SeedData
{
public static void Seed(IApplicationBuilder app)
{
var _dbContext= app.ApplicationServices.GetRequiredService<BlogDbContext>();
_dbContext.Database.EnsureDeleted();
_dbContext.Add<User>(new User { UserName = "Niko", Password ="123",EmailAddress="nikozhao5456#gmail.com",UserType= Models.User.Type.Visitor,RegistDate=System.DateTime.Now});
_dbContext.Add<Admin>(new Admin{EmailAddress="lovezgd888#163.com",Password="123"});
_dbContext.SaveChanges();
}
}
when I Update-Database in the Nuget Package Manage :
An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Cannot resolve scoped service 'Blog.DAL.Context.BlogDbContext' from root provider.
and
Unable to create an object of type 'BlogDbContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

Well Ive solve it by watching the docs,There is something different between Asp.Net Core 1.x and 2.0;I just should write the seed method in the program.cs

Related

IdentitServer4 System.InvalidOperationException: 'No storage mechanism for grants specified

I'm trying to build a simple project using Asp.Net Core and Identity Server 4. But I'm faced with the error
No storage mechanism for grants specified. Use the 'AddInMemoryPersistedGrants' extension method to register a development version"
..My Startup class is:
`
public void ConfigureService(IServiceCollection services)
{
services.AddIdentityServer()
.AddInMemoryApiResources(Config.GetAllApiResources())
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryClients(Config.GetClients())
.AddDeveloperSigningCredential();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
}
`
Notice, when I use AddInMemoryPersistedGrants method, nothing is changed- still the same error. How can I fix it?

My razor pages are not working all of the generate the same error : Localhost page cant be found

This is my startup.cs file
Does anyone know whats going wrong This is my index.cshtml
Alright so my code will be below its very basic startup.cs file and a index.cshtml file with some basic code just for testing
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}}
#page
#DateTime.Now
Try to create a new project and check whether you have the same problem.
And did you apply something to your service side? You can share it.
Or you can try these code first:
ConfigureServices:
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
});
Configure:
app.UseMvcWithDefaultRoute();

OData integration with CosmosDb does not return expected result

I have created a .NET Core 3.1 WebAPI application which connect with Azure Cosmos Db. The WebAPI is returning data from CosmosDb correctly. When I tried to integrate OData to this solution, and tried to query data using the Select method, it does not return expected result.
The following are my code:
StartUp.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOData();
services.AddControllersWithViews();
services.AddSingleton<ICosmosDbService>(InitializeCosmosClientInstanceAsync(Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=ToDo}/{action=Index}/{id?}");
endpoints.EnableDependencyInjection();
endpoints.Select().Filter().OrderBy().Expand();
});
}
}
WebAPI controller:
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
private readonly ICosmosDbService _cosmosDbService;
public ItemsController(ICosmosDbService cosmosDbService)
{
_cosmosDbService = cosmosDbService;
}
// GET: api/<ItemsController>
[HttpGet]
[EnableQuery()]
public async Task<IEnumerable<Item>> Get()
{
return await _cosmosDbService.GetItemsAsync("SELECT * FROM c");
}
}
When I try to retrieve data using the API call(https://localhost:44357/api/items), I am getting expected result:
[{"id":"5f4f5d02-9217-4591-8f8c-2af9fe7d9ae4","name":"Brush","description":"Brush your teeth every night","completed":true,"partitionKey":null},{"id":"6a5edfe3-9c84-4398-bed4-963dbb4a42e3","name":"Excercise","description":"Hit the gym in the evening","completed":true,"partitionKey":null}]
But when I try to use the OData method(https://localhost:44357/api/items?$select=name), I am not getting expected result. Instead, I am getting this:
[{"instance":null,"container":{},"modelID":"7c0ae376-1666-46f8-886f-9bf758824063","untypedInstance":null,"instanceType":null,"useInstanceForProperties":false},{"instance":null,"container":{},"modelID":"7c0ae376-1666-46f8-886f-9bf758824063","untypedInstance":null,"instanceType":null,"useInstanceForenter code hereProperties":false}]
Any idea why it is like this?
There is incompatible situation with the JSON serializer in Asp.Net 3.1. Try to AddNewtonsoftJson.
services.AddControllers(mvcOptions =>
mvcOptions.EnableEndpointRouting = false)
.AddNewtonsoftJson();

Changing ASP Core default route to different controller

I cannnot get my ASP .NET Core MVC site to route to different controller other than Home. I changed the default route in Startup (it is the only route):
app.UseMvc(routes =>
{
routes.MapRoute(name: "default", template: "{controller=profile}/{action=index}/{id?}");
});
my ProfileController looks like:
public class ProfileController : Controller
{
[HttpGet("index")]
public IActionResult Index()
{
return View();
}
...
}
But all I get is 404 returned form the Kestrel server on navigating to base URL.
I've just created a new project and it worked for me. Maybe you're doing something else wrong.
Here's what I did.
Create a new asp.net core web application project (choose MVC template)
Update the default route in the Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
} else {
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=profile}/{action=index}/{id?}");
});
}
Create the Profile Controller:
public class ProfileController : Controller {
// GET: /<controller>/
public IActionResult Index() {
return View();
}
}
Create the Index View for the Profile Controller:
Run the project and the Profile's Index page should open.
UPDATE:
The problem was the [HttpGet("index")] in the Profile Controller.

ASP.Net Core MVC Project cannot configure routes?

I recently started learning ASP.Net Core to develop a MVC Web API. But I cannot even get my hello world running.
In the Startup.cs I wrote:
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
services.AddMvc(routes =>
{
routes.MapRoute(
"default",
"{version?}/{controller=Home}/{action=Index}/{id?}");
});
}
And the console says:
error CS1929: 'MvcOptions' does not contain a definition for 'MapRoute' and the best extension method overload 'MapRouteRouteBuilderExtensions.MapRoute(IRouteBuilder, string, string)' requires a receiver of type 'IRouteBuilder'
Routing You have to add in Configure method not ConfigureService. Try this sample.
Here add mvc to service
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
Here set routes
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}