我配置ServiceStack以启用CORS:
Plugins.Add( new CorsFeature(
allowOriginWhitelist: new List<string>() { "http://localhost", "http://localhost:8080" },
allowCredentials: true,
allowedHeaders: "Content-Type, Allow, Authorization"
) );
PreRequestFilters.Add( ( request, response ) =>
{
if( request.Verb == "OPTIONS" )
{
response.EndRequest();
}
} );
OPTIONS请求和响应看起来很棒,并以http://localhost:8080
为原点成功。但是,随后的GET失败了,因为根据Chrome的说法,它失去了Access-Control-Allow-Origin标头。
这是错误:
否&#39;访问控制 - 允许 - 来源&#39;标头出现在请求的资源上。因此,不允许原始
http://localhost:8080
访问。
以下是请求:
GET /app/api/operations/metadata HTTP/1.1
Host: dummy.domain.net
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Content-Type: application/json; charset=utf-8
Referer: http://localhost:8080/dev.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
以下是回复:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Vary: Accept
Server: Microsoft-IIS/7.5
X-Powered-By: ServiceStack/4.034 Win32NT/.NET
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Allow, Authorization
Access-Control-Allow-Credentials: true
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 20 Dec 2014 17:22:38 GMT
Content-Length: 38203
请注意缺少的Access-Control-Allow-Origin标头。
答案 0 :(得分:3)
ServiceStack的CorsFeature already handles OPTIONS requests因此您需要删除,这样才不会使请求短路。
//Should be removed
PreRequestFilters.Add((request,response) => {
if (request.Verb == "OPTIONS" )
{
response.EndRequest();
}
});
我在自定义Http处理程序中添加了对原始白名单的支持,例如/operations/metadata
in this commit。这现在可以按预期工作,如http://test.servicestack.net(source code)中所示:
HTTP请求
GET http://test.servicestack.net/operations/metadata HTTP/1.1
Host: test.servicestack.net
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Origin: http://localhost:8080
HTTP响应
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html
Vary: Accept
Server: Microsoft-IIS/8.5
Access-Control-Allow-Origin: http://localhost:8080
X-Powered-By: ServiceStack/4.00 Win32NT/.NET
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Allow, Authorization
Access-Control-Allow-Credentials: true
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 21 Dec 2014 00:30:39 GMT
Content-Length: 17027
此更改可从 v4.0.35 + 获得,现在为available on MyGet。