Poly
Poly

Reputation: 427

.Net MVC API Access-Control-Allow-Origin error upon Ajax POST request

I have a .Net solution in VS2013, with multiple project on separate ports. I am sending data back and forth between two of these projects, mainly an API project on localhost:4348 and a front-end project on localhost:33630.

I am using jQuery to make ajax calls to the API and sending data through the POST request, an example of the POST request:

$.ajax({
    type: "POST",
    url: 'http://localhost:4348/api/Viewer/GetSearchResult',
    data: searchObject,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (responseData, textStatus, jqXHR) {
        console.log(responseData);
    },
    error: function (responseData, textStatus, errorThrown) {
        console.log("Text status:", textStatus);
    }
});

The searchObject structure is as follows, where its items get populated at some point before the ajax call:

searchObject.generalSearchList = [];
searchObject.indexesSearchList = [];
searchObject.searchType = '';
searchObject.language = '';
searchObject.id = '';
searchObject.selector = '';

The API project does not allow me to add the followings settings to Web.config file:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

Doing that raises this error on any API I try to call:

XMLHttpRequest cannot load http://localhost:4348/api/Viewer/GetTrees?Lang=en-US. The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:33630, *', but only one is allowed. Origin 'http://localhost:33630' is therefore not allowed access.

So without that option set, when I try to call the API with POST method, I get the following error:

XMLHttpRequest cannot load http://localhost:4348/api/Viewer/GetSearchResult. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:33630' is therefore not allowed access. The response had HTTP status code 500.

Having the contentType set to application/json; charset=utf-8 fires a preflight request of type OPTIONS. Somewhere along the lines of Visual Studio, it is adding permission to the origin http://localhost:33630 on GET requests, but not on OPTIONS requests. And I cannot override the permission as I mentioned in the Web.config file.

I have done a lot of research and tested many scenarios before posting here, including adding

<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />

to the web.config file in the API project.

Needless to say I am desperate to understand the cause of the error and solving it as I have been stuck with this for about a week now. Tested on Chrome and Firefox.

Upvotes: 4

Views: 1706

Answers (1)

Dandy
Dandy

Reputation: 2177

You can enable CORS in your WebApiConfig.cs also.

  1. Install nuget Microsoft.AspNet.WebApi.Cors
  2. Enable cors in WebApiConfig.cs

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
            // Other config lines
        }
    }
    

This will enable CORS gloablly, you can decorate your api controller or even single api method with

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}

to target specific controllers or method. You can read more about enabling CORS in WebAPI projects at http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Upvotes: 2

Related Questions