0
votes

My Web Application(ASP.NET MVC5) hosted in Server A and Rest Service(WebAPI) is hosted in Server B. When the application access the WebAPI through IE11 , it works fine but in chrome, i got the error message as no access-control-allow-origin header is present

After Googling, i added this in the Web.config of WebAPI

<httpProtocol>
        <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
add name="Access-Control-Allow-Credentials" value="true" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
    </httpProtocol>

And the below one in the client side call

var config = {
            headers: {

                'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': '*',
                'Access-Control-Allow-Credentials': true,
                'X-Requested-With': 'XmlHttpRequest'
            }
        };

        $http.get(url, config).success(function (data) {
            var filteredData = data;
})

Now i m getting authorization error XMLHttpRequest cannot load (URL) Invalid HTTP status code 401

Also i have one more query, to overcome CORS error, do we need to add information only in client side or in server side or both required?

1

1 Answers

0
votes

You should not need to make any specific CORS configurations in your client-side request. The browser (Chrome, in your case) should send the proper headers.

EDIT: if you are support credentials on the server side (see note below), then you need to include the following in your ajax requests:

xhrFields: { withCredentials: true }

See xhrFields documentation.

For the server side, I would recommend installing the Microsoft.AspNet.WebApi.Cors NuGet package, and then follow these configuration instructions. In particular, see this section which explains how you can enable CORS per action, per controller, or globally for all Web API controllers in your application.

For example:

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
public HttpResponseMessage GetItem(int id) { ... }

If you are going to use the Access-Control-Allow-Credentials header with a value of true then the Access-Control-Allow-Origin header cannot be *. It has to be set to one or more specific domains.