问题描述
从我的理解,当启用CORS相应,响应模型应该包括以下标题信息(前提是我想允许一切):
c>> c> c> 在 Startup.Configure 方法中,因为您需要在MVC中间件之前应用CORS中间件。public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory)
{
...
//在MVC之前添加CORS中间件
app.UseCors(AllowAll);
app.UseMvc(...);
}
否则,请求将在应用CORS中间件之前完成。这是因为调用,最后添加,此中间件只在未找到请求的路由处理程序时才执行下一个配置的中间件。
From what I understand, when enabled CORS accordingly, the response model should include the following header information (provided that I want to allow everything):
Access-Control-Allow-Origin: * Access-Control-Allow-Method: * Access-Control-Allow-Header: *Enabling it in Startup:
public void ConfigureServices(IServiceCollection services) { //... services.AddCors(); services.ConfigureCors(options => { options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials()); }); //... } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //... app.UseCors("AllowAll"); //... }The problem is that none of these headers are returned and I get the following error when trying to request from the API:
解决方案Make sure you add app.UseCors before app.UseMvc in your Startup.Configure method, because you need the CORS middleware to be applied before the MVC middleware.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { ... //Add CORS middleware before MVC app.UseCors("AllowAll"); app.UseMvc(...); }Otherwise the request will be finished before the CORS middleware is applied. This is because UseMvc calls UseRouter which ends up adding the RouterMiddleware, and this middleware only executes the next configured middleware when a route handler wasn't found for the request.
这篇关于ASP.NET 5:Access-Control-Allow-Origin作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!