WebApi DelegatingHandler未调用预检CORS请求

时间:2013-09-09 18:34:08

标签: asp.net-web-api cors

我正在尝试为我的WebApi控制器实现CORS支持,我正在关注示例here

我的处理程序如下所示:

/// <summary>
/// Taken from http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx
/// </summary>
public class CorsHandler : DelegatingHandler
{
    private const string Origin = "Origin";
    private const string AccessControlRequestMethod = "Access-Control-Request-Method";
    private const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
    private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
    private const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
    private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
    private const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials";

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var isCorsRequest = request.Headers.Contains(Origin);
        var isPreflightRequest = request.Method == HttpMethod.Options;
        if (isCorsRequest)
        {
            if (isPreflightRequest)
            {
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                var accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                if (accessControlRequestMethod != null)
                {
                    response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                }

                var requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
                if (!string.IsNullOrEmpty(requestedHeaders))
                {
                    response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                }
                response.Headers.Add(AccessControlAllowCredentials, "true");

                var tcs = new TaskCompletionSource<HttpResponseMessage>();
                tcs.SetResult(response);
                return response;
            }

            var resp = await base.SendAsync(request, cancellationToken);
            resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
            resp.Headers.Add(AccessControlAllowHeaders, "*");
            resp.Headers.Add(AccessControlAllowCredentials, "true");
            return resp;
        }
        return await base.SendAsync(request, cancellationToken);
    }
}

在我的WebApiConfig类中,我正在注册该处理程序:

config.MessageHandlers.Add(new CorsHandler());

它被称为“GET”请求。但是没有要求任何需要预检批准的请求。请求如下所示:

Request OPTIONS /api/campaigns/1002/customerusers/1008 HTTP/1.1
Accept  */*
Origin  http://app.dev.alanta.com
Access-Control-Request-Method   DELETE
Access-Control-Request-Headers  accept
Accept-Encoding gzip, deflate
User-Agent  Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)
Host    dev.payboard.com
Content-Length  0
DNT 1
Connection  Keep-Alive
Cache-Control   no-cache

但正如我所说,处理程序永远不会被调用OPTIONS动词。

我认为可能有其他处理程序在某处干扰了这个,但我已经删除了所有可能的候选人,到目前为止没有运气。

我的另一个理论是它没有识别OPTIONS动词的特定路径,因此它永远不会将请求传递给WebApi子系统,而是在其他地方处理它。但我并不完全清楚如何解决这个问题。

建议?

1 个答案:

答案 0 :(得分:7)

将以下内容添加到web.config:

<handlers>
    <remove name="OPTIONSVerbHandler" />
</handlers>