OPTIONS Verb for Routes with custom CORS headers

假装没事ソ 提交于 2019-12-11 02:22:29

问题


Lets say I have a route like this:

[Route("/users/{Id}", "DELETE")]
public class DeleteUser
{
    public Guid Id { get; set; }
}

If I am using CORS with a custom header, an OPTIONS preflight request will be sent out. This will happen on all requests. With the above route, the route will fire, but the OPTIONS will 404 and the ajax error handler will fire.

I could modify the route to be [Route("/users/{Id}", "DELETE OPTIONS")] but I would need to do this on every route I have. Is there a way to globally allow OPTIONS for all custom routes?

Edit

Since it looks like this behavior is incorrect when a RequestFilter allows for OPTIONS, I am temporarily using an Subclassed Attribute that just automatically adds OPTIONS to the verbs

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ServiceRoute : RouteAttribute
{
    public ServiceRoute(string path) : base(path) {}
    public ServiceRoute(string path, string verbs) 
           : base(path, string.Format("{0} OPTIONS", verbs)) {}
}

回答1:


As seen in this earlier answer, you can add globally enable CORS for all options request by adding the CorsFeature plugin:

Plugins.Add(new CorsFeature()); //Registers global CORS Headers

If you then want to, you can simply add a PreRequest filter to emit all Global Headers (e.g. registered in CorsFeature) and short-circuit all OPTIONS requests with:

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


来源:https://stackoverflow.com/questions/16365577/options-verb-for-routes-with-custom-cors-headers

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