2

假设我有这样的路线:

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

如果我使用带有自定义标头的 CORS,则会发送一个 OPTIONS 预检请求。这将发生在所有请求上。使用上述路由,路由将触发,但 OPTIONS 将 404 并且 ajax 错误处理程序将触发。

我可以将路线修改为,[Route("/users/{Id}", "DELETE OPTIONS")]但我需要在我拥有的每条路线上都这样做。有没有办法全局允许所有自定义路线的选项?

编辑

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

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

1 回答 1

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();
});
于 2013-05-03T20:06:36.563 回答