根据我的理解,当相应地启用CORS时,响应模型应包括以下标头信息(假设我想允许所有内容):
Access-Control-Allow-Origin: * Access-Control-Allow-Method: * Access-Control-Allow-Header: *
启用它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"); //... }
问题是这些标头都没有返回,并且在尝试从API请求时出现以下错误:
对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.原产地" :HTTP //本地主机,因此"是不允许访问.
Daniel J.G... 19
确保在方法app.UseCors
之前添加,因为您需要在MVC中间件之前应用CORS中间件.app.UseMvc
Startup.Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { ... //Add CORS middleware before MVC app.UseCors("AllowAll"); app.UseMvc(...); }
否则,请求将在应用CORS中间件之前完成.这是因为最终添加的UseMvc
调用,并且当找不到请求的路由处理程序时,此中间件仅执行下一个配置的中间件.UseRouter
RouterMiddleware
确保在方法app.UseCors
之前添加,因为您需要在MVC中间件之前应用CORS中间件.app.UseMvc
Startup.Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { ... //Add CORS middleware before MVC app.UseCors("AllowAll"); app.UseMvc(...); }
否则,请求将在应用CORS中间件之前完成.这是因为最终添加的UseMvc
调用,并且当找不到请求的路由处理程序时,此中间件仅执行下一个配置的中间件.UseRouter
RouterMiddleware