.NET Web API CORS PreFlight Request

Milan Gatyas picture Milan Gatyas · Dec 27, 2013 · Viewed 28.1k times · Source

I have some trouble make PUT and DELETE CORS request to Web API on other domain.

I've coded API by tutorial http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#create-webapi-project.

GET and POST Requests works fine, but DELETE and PUT doesn't. I get this message:

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When I add code to WebConfig suggested on CORS support for PUT and DELETE with ASP.NET Web API , I get only first error.

Can anyone help me with this please?

Answer

MCurbelo picture MCurbelo · Jan 28, 2015

You can add a handler to deal with this type of request.

Create a class derive from "DelegatingHandler":

public class PreflightRequestsHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
        {
            var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
            // Define and add values to variables: origins, headers, methods (can be global)               
            response.Headers.Add("Access-Control-Allow-Origin", origins);
            response.Headers.Add("Access-Control-Allow-Headers", headers);
            response.Headers.Add("Access-Control-Allow-Methods", methods);
            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            tsc.SetResult(response);
            return tsc.Task;
        }
        return base.SendAsync(request, cancellationToken);
    }

}

Later in WebApiconfig.cs in Register method add this:

public static void Register(HttpConfiguration config)
{
    // Define and add values to variables: origins, headers, methods (can be global) 
    // Enable global CORS
    config.EnableCors(new EnableCorsAttribute(origins, headers, methods));

    // Add handler to deal with preflight requests, this is the important part
    config.MessageHandlers.Add(new PreflightRequestsHandler()); // Defined above
    .
    .
    .
}