【发布时间】:2016-01-22 20:03:51
【问题描述】:
在 beta7 中,CORS 可以这样设置:
// in the ConfigurationServices
services.AddMvc();
services.ConfigureCors(options =>
{
// set cors settings...
});
//...
// in the Startup.Configure method
app.UseCors();
app.UseMvc();
它就像一个魅力,但 beta8 打破了它。我发现了这个 SO 问题: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 request。这是 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 模板(测试版 8)重现此问题。
当我用[EnableCors] 和[Authorize] 装饰控制器或方法时,它返回 401 Unauthorized(或 302 重定向到登录页面)。
编辑2 事实证明,这是我犯的一个愚蠢的错误。我自己回答了问题所在。
【问题讨论】:
标签: c# cors asp.net-core