ServiceStack returns 405 on OPTIONS request

限于喜欢 提交于 2019-11-29 11:31:07

405 in ServiceStack means that method has not been implemented.

So you need to add a handler for the Options verb. The method body can be empty, e.g:

public MyService : Service 
{ 
    public void Options(HomeInterface request) {}
}

If you wanted to allow all Options requests (i.e. regardless of which service it is), you can register a global request filter like:

this.RequestFilters.Add((httpReq, httpRes, requestDto) => {
   //Handles Request and closes Responses after emitting global HTTP Headers
    if (httpReq.Method == "OPTIONS") 
        httpRes.EndServiceStackRequest();
});

You can use the same logic in Filter Attributes if you want more fine-grained control over how Option requests are handled.

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();
    }
});

I was a bit confused about this behavior. Did not wanted to make dummy Options() methods on every service and add fake routes on every Dto class. All I've needed - that ServiceStack AppHost responsed for EVERY 'OPTIONS' request, on every url, with same behavior. So this is what I've ended with.

Created my own handler for Options:

public class OptionsRequestHandler : IHttpHandler, IServiceStackHttpHandler
{
    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        ProcessRequest(null, new HttpResponseWrapper(context.Response), null);          
    }

    public void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
    {
        httpRes.EndServiceStackRequest();
        return;
    }
}

Then added it in host Configure method:

this.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) =>
{
    if ("OPTIONS".Equals(httpMethod, System.StringComparison.InvariantCultureIgnoreCase))
        return new OptionsRequestHandler();
    else return null;
});

And surely did not forget the CorsFeature:

host.Plugins.Add(new ServiceStack.ServiceInterface.Cors.CorsFeature());

So this way ServiceStack responds with "200 OK" on every request with "OPTIONS" header, regardless of url, dto and service declarations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!