【发布时间】:2015-03-05 22:59:17
【问题描述】:
我们在 ServiceStack 4 中使用 RESTful API 的 CORS 功能遇到了一些障碍。
我们希望将 cookie 发送到 api,因为 SS 会话在 cookie 中,因此我们在命中 API 的 Angular 客户端中使用“WithCredentials”=true 进行 AJAX 调用。
由于 Chrome(至少)不喜欢带有 WithCredentials 的 Access-Control-Allow-Origin 通配符,我们添加了一个预请求过滤器以在 Access-Control-Allow-Origin 标头中回显请求者的来源,例如所以:
private void ConfigureCors()
{
Plugins.Add(new CorsFeature(
allowedHeaders: "Content-Type",
allowCredentials: true,
allowedOrigins: ""));
PreRequestFilters.Add((httpReq, httpRes) =>
{
string origin = httpReq.Headers.Get("Origin");
if (origin != null)
{
httpRes.AddHeader(HttpHeaders.AllowOrigin, origin);
}
else
{
// Add the dev localhost header.
httpRes.AddHeader(HttpHeaders.AllowOrigin, "http://localhost:9000");
}
});
PreRequestFilters.Add((httpReq, httpRes) =>
{
//Handles Request and closes Responses after emitting global HTTP Headers
if (httpReq.Verb == "OPTIONS")
{
httpRes.EndRequest();
}
});
}
但是,我们遇到了 OPTIONS 请求的障碍,因为 SS 服务在请求结束时没有返回 Access-Control-Allow-Origin 标头。这会使 Chrome 拒绝来电。
我们尝试在 OPTIONS 的预请求过滤器中放置一个显式标头,但它仍然没有为 OPTIONS 调用返回 ACAO 标头:
PreRequestFilters.Add((httpReq, httpRes) =>
{
//Handles Request and closes Responses after emitting global HTTP Headers
if (httpReq.Verb == "OPTIONS")
{
httpRes.AddHeader(HttpHeaders.AllowOrigin, "*");
httpRes.EndRequest();
}
});
这似乎以前必须处理过,但我们在 StackOverflow 上找不到类似的东西。
我们是否对 OPTIONS 预请求过滤器做错了什么?为什么它不返回 Access-Control-Allow-Origin 标头?
【问题讨论】:
-
感谢上帝的帖子,我对 CORS 感到疯狂。你用你的例子帮助我,并说用 angularjs 打开 WithCredentials !谢谢
标签: c# http-headers cors servicestack