Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi DelegatingHandler not called for preflight CORS requests

I'm trying to implement CORS support for my WebApi controllers, and I'm following the example here.

My handler looks like this:

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

In my WebApiConfig class, I'm registering that handler like so:

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

And it's getting called for "GET" requests. But it's not getting called for any requests that require preflight approval. The request looks like this:

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

But as I said, the handler never gets called for the OPTIONS verb.

I thought that there might be some other handler interfering with this somewhere, but I've removed all the likely candidates, and no luck so far.

My other theory is that it's not recognizing that particular route for the OPTIONS verb, and so it's never handing off the request to the WebApi subsystem, and it's getting handled somewhere else. But I'm not entirely clear how to fix that.

Suggestions?

like image 611
Ken Smith Avatar asked Sep 09 '13 18:09

Ken Smith


1 Answers

Add to web.config the following:

<handlers>
    <remove name="OPTIONSVerbHandler" />
</handlers>
like image 83
Vladimir Avatar answered Nov 03 '22 02:11

Vladimir