ServiceStack应OPTIONS请求返回405 [英] ServiceStack returns 405 on OPTIONS request
问题描述
我正在使用ServiceStack构建REST Web服务。我想允许跨域请求,所以我注册了CorsFeature插件。
I'm building a REST webservice using ServiceStack. I want to allow cross-domain request, so I registered the CorsFeature plugin.
我的AppHost如下所示:
My AppHost looks as follows:
public class HomeAppHost : AppHostHttpListenerBase
{
public Context Context { get; set; }
public HomeAppHost(Context context)
: base("HomeAutomation", typeof(HomeInterfaceService).Assembly)
{
Context = context;
}
public override void Configure(Funq.Container container)
{
Plugins.Add(new CorsFeature());
Routes
.Add<HomeInterface>("/HomeInterface")
.Add<HomeInterface>("/HomeInterface/{Id}")
.Add<ViewModel>("/ViewModel")
.Add<FunctionInput>("/Function")
;
}
}
然后,当对服务发出OPTIONS请求时,结果为405方法不允许:
Then, when an OPTIONS request is made to the service, it results in a 405 Method Not Allowed:
请求:
OPTIONS /Function HTTP/1.1
Host: localhost:1337
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0 FirePHP/0.7.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: nl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Origin: http://localhost
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
x-insight: activate
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
响应:
HTTP/1.1 405 Method Not Allowed
Content-Length: 1837
Content-Type: application/xml
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 15 Feb 2013 20:19:33 GMT
编辑
向服务中添加空的Options方法确实确实防止了405的触发。但是,响应似乎为空:
Adding an empty Options method to the service does indeed prevent the 405 from being triggered. However, the response seems to be empty:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Server: Microsoft-HTTPAPI/2.0
Date: Sat, 16 Feb 2013 08:44:21 GMT
添加以下内容也会给我一个空的响应:
Adding the following also gives me an empty response:
RequestFilters.Add((httpReq, httpRes, requestDto) =>
{
//Handles Request and closes Responses after emitting global HTTP Headers
if (httpReq.HttpMethod == "OPTIONS")
httpRes.End();
});
我必须将httpReq.Method更改为httpReq.HttpMethod,并将httpRes.EndServiceStackRequest()更改为httpRes.End ()。这样对吗?
I had to change httpReq.Method to httpReq.HttpMethod and httpRes.EndServiceStackRequest() to httpRes.End(). Is this correct?
推荐答案
不确定这是否是正确的方法,但是我现在使用请求过滤器自己处理CORS:
Not sure whether this is the right way to go, but I'm now handling the CORS myself using a request filter:
RequestFilters.Add((httpReq, httpRes, requestDto) =>
{
httpRes.AddHeader("Access-Control-Allow-Origin", "*");
if (httpReq.HttpMethod == "OPTIONS")
{
httpRes.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
httpRes.AddHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
httpRes.End();
}
});
这篇关于ServiceStack应OPTIONS请求返回405的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!