ThomasE
ThomasE

Reputation: 409

ASP.Net WEB API 2.0 - CORS

I'm struggling with an ASP.Net WEB API 2.0 problem that seems to be related to CORS (Cross Origin Resource Sharing).

At my WEB API, services.xyz site I have made the following cofiguration in web.config under System.WebServer:

  <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://xyz.web" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

And at my ASP.Net Web Site xyz.web that is using the WEB API, I have no problems when calling GET methods on the WEB API.

$http({ method: 'GET', url: 'http://services.xyz.dk/api/WarningSentences/GetWarningSentencesById?warningSentenceId=' + value })
.success(function (data) {
    deferred.resolve(data);
})

But as soon as I try to do a POST from xyz.web to services.xyz, FireFox tells me that I'm trying to do cross origin API calls that are not allowed. Chrome browser just gives me a http status 405 (Not Allowed).

 $http({
     method: 'POST',
     url: 'http://services.xyz.dk/api/WarningSentences/Update',
     data: value,
     dataType: 'json',
     headers: {"Content-Type": "application/json"}
 })

And If I remove the CORS configuration at services.xyz, everything breaks down which is clear. So it seems that it is allowed to do GET API calls using the CORS configuration, but not POST API Calls...

Why?

Upvotes: 0

Views: 242

Answers (2)

Omar.Alani
Omar.Alani

Reputation: 4130

Try use "Microsoft.AspNet.WebApi.Cors" library instead, it is a better and cleaner way to enable CORS for Web APIs, and you don't need to add the headers into the web.config.

See this link for details of how to do it.

Hope that helps.

Upvotes: 2

ThomasE
ThomasE

Reputation: 409

Got it fixed by adding the the Application_BeginRequest event to the Global.asax on WEB API website.

protected void Application_BeginRequest()
    {
        if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
        {
            Response.Flush();
        }
    }

Upvotes: 0

Related Questions