具有自定义CORS标头的路线动词 [英] OPTIONS Verb for Routes with custom CORS headers

查看:96
本文介绍了具有自定义CORS标头的路线动词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一条这样的路线:

Lets say I have a route like this:

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

如果我将CORS与自定义标头一起使用,则OPTIONS预检请求将被发送出去。这将在所有请求上发生。使用上述路由,该路由将被触发,但OPTIONS将被404触发,而ajax错误处理程序将被触发。

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.

我可以将路由修改为 [Route( / users / {Id}, DELETE OPTIONS)] ,但我需要在我拥有的每条路线上执行此操作。有没有一种方法可以全局允许所有自定义路线使用OPTIONS?

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?

因为它看起来像这种行为 RequestFilter 允许使用OPTIONS是不正确的,我暂时使用的是一个子类属性,该属性只是将OPTIONS自动添加到动词

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)) {}
}


推荐答案

在此更早的答案,您可以通过添加 CorsFeature 插件:

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

如果您愿意,可以简单地添加一个PreRequest过滤器以发出所有全局标头(例如在CorsFeature中注册),并使用以下命令短路所有 OPTIONS 请求:

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

这篇关于具有自定义CORS标头的路线动词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆