在beta7中,CORS能够像这样设置:
// in the ConfigurationServices
services.AddMvc();
services.ConfigureCors(options =>
{
// set cors settings...
});
//...
// in the Startup.Configure method
app.UseCors();
app.UseMvc();
它就像一个魅力,但beta8打破了它.我发现了这个问题:Why Cors doesn’t work after update to beta8 on ASP.NET 5?,并修改如下:
// in Startup.ConfigureServices method
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
// allow them all
builder.AllowAnyHeader();
builder.AllowAnyMethod();
builder.AllowAnyOrigin();
builder.AllowCredentials();
});
});
services.AddMvc();
//...
// in the Startup.Configure method
app.UseMvc();
//...
// in the Controller
[EnableCors("CorsPolicy")]
public IActionResult Get()
{
return OK();
}
是的它再次起作用,但是当我添加[Authorize(“Bearer”)]时,控制器通过ajax调用返回401 Unauthorized for OPTIONS请求.这是HTTP请求和响应.
[请求]
OPTIONS https://api.mywebsite.net/ HTTP/1.1
Accept: */*
Origin: https://myanotherwebsite.net
Access-Control-Request-Method: GET
Access-Control-Request-Headers: accept, authorization
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko
Host: api.mywebsite.net
Connection: Keep-Alive
Cache-Control: no-cache
[响应]
HTTP/1.1 401 Unauthorized
Content-Length: 0
Server: Microsoft-IIS/8.0
WWW-Authenticate: Bearer
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=...;Path=/;Domain=api.mywebsite.net
Date: Fri, 23 Oct 2015 09:56:34 GMT
如何在ASP.NET 5 beta8中使用[Authorization]属性启用CORS?
编辑
我能够使用默认的ASP.NET MV C6模板(beta 8)重现此问题.
当我使用[EnableCors]和[Authorize]装饰控制器或方法时,它返回401 Unauthorized(或302重定向到登录页面).
EDIT2
事实证明,这是我的一个愚蠢的错误.我回答了自己是什么问题.
最佳答案 好吧,这是我的愚蠢错误.我对Microsoft.AspNet.Mvc.Cors和Microsoft.AspNet.Cors感到困惑.
前一个是关于OWIN中间件,另一个是关于Mvc过滤器.我没有在Project.json中添加Microsoft.AspNet.Cors,也没有在Configures()中添加app.UseCors().
ConfigureServices()中的AddCors()和Configure()中的UseCors()都需要协同工作.
这可能是CORS的基本设置.
(在Project.json中)
"dependencies": {
...
"Microsoft.AspNet.Cors": "6.0.0-beta8",
"Microsoft.AspNet.Mvc.Cors": "6.0.0-beta8",
...
}
(在Startup.cs中)
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
// ...build cors options...
});
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseMvc();
}
或这个:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseCors(builder =>
{
// ...default cors options...
});
app.UseMvc();
}
希望没有人像我一样犯愚蠢的错误.