OPTIONS Verb for Routes with custom CORS headers

2019-07-18 04:42发布

问题:

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