1

I'm having trouble getting CORS to work with WebAPI. I'm implementing the ICorsPolicyProvider like this:

public class CustomCorsPolicy : Attribute, ICorsPolicyProvider 
{
    private CorsPolicy _policy;

    public CustomCorsPolicy()
    {
        _policy = new CorsPolicy
        {
            AllowAnyMethod = true,
            AllowAnyHeader = true
        };

        _policy.Origins.Add("http://****");
        _policy.Origins.Add("http://localhost:8080");
    }
    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(_policy);
    }
}

This works fine for GET, PUT, and DELETE methods but for POST methods the preflight request doesn't render the Access-Control-Allow- header in the response.

This is what the preflight response looks like for PUT (which works):

Access-Control-Allow-Headers:content-type
Access-Control-Allow-Methods:PUT
Access-Control-Allow-Origin:http://localhost:8080
Cache-Control:no-cache
Content-Length:0
Date:Fri, 30 Jan 2015 21:37:42 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpccmVwb1xmb3NfYWxsXHNyY1xFbGxpb3R0LkZyb250T2ZmaWNlLkRhdGFNYW5hZ2VtZW50XGFwaVxmaXhpbmdDb25maWd1cmF0aW9uc1wwRUg1Q185OC43NTAsOVw=?=

This is what the preflight response looks like for POST (which doesn't work):

Allow:OPTIONS, TRACE, GET, HEAD, POST
Content-Length:0
Date:Fri, 30 Jan 2015 21:56:22 GMT
Public:OPTIONS, TRACE, GET, HEAD, POST
Server:Microsoft-IIS/8.0
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpccmVwb1xmb3NfYWxsXHNyY1xFbGxpb3R0LkZyb250T2ZmaWNlLkRhdGFNYW5hZ2VtZW50XGFwaVxmaXhpbmdzXA==?=
Charlie
  • 10,227
  • 10
  • 51
  • 92

1 Answers1

0

I solved this using this solution:

https://stackoverflow.com/a/14631068/85733

I was using the CORS nuget and I don't think it works properly. Don't waste you time with it. This works fine for the preflights:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
       HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }

    }
Community
  • 1
  • 1
Charlie
  • 10,227
  • 10
  • 51
  • 92