starup file changes in Asp.net core - asp.net-core

I am Upgrading .Net core web api solution 2.2 to 3.1
I have question what should i use in statrup.cs file for 3.1
// currently i am using this
public Startup(Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
public Startup(Microsoft.Extensions.Hosting.IHostingEnvironment env)

I am Upgrading .Net core web api solution 2.2 to 3.1 I have question what should i use in statrup.cs file for 3.1
If you create a new ASP.NET Core 3.1 API project using the API template, you would find it uses below Startup class.
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.AddControllers();
}
// 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();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Compare it with old one, you can find the following changes:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2) is changed to services.AddControllers()
IHostingEnvironment is obsolete, and it uses IWebHostEnvironment now
app.UseEndpoints, endpoint routing is used

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?

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();

.NET Core compression does not work in my controller

I just created a new .NET Core 3.1 Web API project based by the template in VS 2019, and I added code following the official example in startup.cs like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
but the compression middleware does not work
webapi response in browser
.Net Core Response Compression is disabled by default for HTTPS traffic, which it appears you are using. Try changing your call to AddResponseCompression() to turn it on for https.
services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
});
You can see the MS docs for use of response compression with https, as there are security implications noted in the article. https://learn.microsoft.com/en-us/aspnet/core/performance/response-compression?view=aspnetcore-3.1#compression-with-secure-protocol

How to set default razor page route with asp.net 3.0 middleware

So to setup endpoint routing in asp.net core 3.x, we do something like this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
}
How/where can we define a "default" page route other than index?
The easiest solution would be to manually add route to the custom page in ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages(o => o.Conventions.AddPageRoute("/CustomPage", ""));
}
With this solution you need to rename or remove Index page to avoid AmbiguousMatchException
This is an example of a default route.
app.UseEndpoints(endpoint =>
{
endpoint.MapDefaultControllerRoute();
});

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

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