问题描述
据我了解,当相应启用 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: *
在 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 请求时收到以下错误:
The problem is that none of these headers are returned and I get the following error when trying to request from the API:
对预检请求的响应未通过访问控制检查:否请求中存在Access-Control-Allow-Origin"标头资源.Origin 'http://localhost' 因此不允许访问.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
推荐答案
确保在 Startup.Configure 中的
app.UseMvc
之前添加 app.UseCors
方法,因为你需要在 MVC 中间件之前应用 CORS 中间件.
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(...);
}
否则请求将在应用 CORS 中间件之前完成.这是因为 UseMvc
调用 UseRouter
最终添加了 RouterMiddleware
,并且此中间件仅在未找到请求的路由处理程序时执行下一个配置的中间件.
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:响应中的访问控制允许来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!