【发布时间】:2016-12-14 17:57:18
【问题描述】:
我们正在开发具有移动部分和 Web UI 的应用程序。 Web UI 使用 Angular,我们在后端配置 cors 时遇到问题。我们的代码如下所示(只是对我们的问题很重要的代码):
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("AllowAll");
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//Add Cors support to the service
services.AddCors(
options => options.AddPolicy(
"AllowAll", p => p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
)
);
}
从文档和stackoverflow 上的其他帖子来看,这应该可以,但不是。我们错过了什么?
thnx
编辑:
这是来自 POSTMAN 的请求:
curl 'https://guw.azurewebsites.net/api/token' -X OPTIONS -H '编译指示: 无缓存' -H '访问控制请求方法:POST' -H '来源: http://localhost:9000' -H '接受编码:gzip、deflate、sdch、br' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36' -H '接受:/' -H '缓存控制:无缓存' -H '引用者:http://localhost:9000/' -H '连接:保持活动' -H '访问控制请求标头:接受, 授权,内容类型'--压缩
您可以在邮递员中导入它并查看它。此请求由 Angular 应用发送。
希望这会有所帮助。
最后我决定在我的中间件中添加这个方法:
private void AddCors(HttpContext context)
{
context.Response.Headers.Add("Access-Control-Allow-Headers",
new string[] { "Authorization", "Content-Type" });
context.Response.Headers.Add("Access-Control-Allow-Methods",
new string[] { "OPTIONS", "POST", "GET", "DELETE", "PUT" });
IEnumerable<string> allowedUrls = new List<string>()
{
"http://localhost:8100",
"http://localhost:9000"
};
if (allowedUrls.Count() > 0)
{
foreach(string x in allowedUrls)
{
var origin = context.Request.Headers.FirstOrDefault(
key => key.Key == "Origin");
var found = x.ToLower() == origin.Value.ToString().ToLower();
if (found)
{
context.Response.Headers.Add("Access-Control-Allow-Origin",
new string[] { origin.Value });
}
}
}
return;
}
编辑:
这很好,但在逻辑上它没有按我的需要工作,所以我最终在我的中间件类中使用了这个,而且效果很好:
// Add CORS to every response
context.Response.Headers.Add("Access-Control-Allow-Headers",
new string[] { "Authorization", "Content-Type" });
context.Response.Headers.Add("Access-Control-Allow-Methods",
new string[] { "OPTIONS", "POST", "GET", "DELETE", "PUT" });
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
if (context.Request.Method.Equals("OPTIONS", StringComparison.Ordinal))
{
context.Response.StatusCode = 204;
return _next(context);
}
谢谢
【问题讨论】:
-
“这应该可以,但不行”您需要edit添加有关您如何测试它以及为什么它“但不行”的详细信息
-
我最后在中间件中添加了我的方法。编辑了我的帖子。
-
@Wasyster Vow,为什么要添加这么多代码? MVC 不是已经为你做这件事了吗?
-
信不信由你,它没有做,我包括了一切。尝试了每种组合来弄清楚,但从未奏效。
-
为了搜索者的利益,我在 CORS 上遇到了类似的问题 - 在此处发布了我的答案 -> stackoverflow.com/a/40286658/852806
标签: asp.net-core cors asp.net-core-mvc