Riad Riad - 1 month ago 11
ASP.NET (C#) Question

how to allow CORS for ASP.NET

I have a problem trying to make a request from JS/Ajax to my WebAPI. In my solution I have a Web API that is published on srv02:2400 and my website that is published on srv02:2300

When I navigate to the page http://srv02:2300/all-requests.aspx, the page is loading fine except the data that is supposed to come form my API

and I am getting the error:

XMLHttpRequest cannot load http://srv02:2400/api/requests/find/1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://srv02:2300' is therefore not allowed access. The response had HTTP status code 400.


However, If I take the url http://srv02:2400/api/requests/find/1 and paste it in a browser, it is getting me the correct JSON list!.

I tried to enable the CORS globally as it is recommended here in my API by:


  1. Installing the package Microsoft.AspNet.WebApi.Cors

  2. Updating my WebApiConfig.cs by addding the following:

    var cors = new EnableCorsAttribute("http://srv02:2400", "", "");
    config.EnableCors(cors);



However, this did not work.

As I mentioned before, I am doing my request as Ajax reqeusts

$.ajax({
url: "http://srv02:2400/api/requests/find/" + id,
type: "GET",
dataType: 'json',
contentType: 'application/json',
success: function (requests) {
console.log('success');
},
error: function (err) {
if (err) {
console.log(err);
}
}
});


I tried to change json to jsonp as it is recommended here but it did not work.

Any idea of how to solve the problem here.

Thank you!

Answer

Your global attribute looks wrong.

I think you want two things to change.

  • Your CORS url should be the URL of the application you want to allow (not your apis url) ie :2300 not :2400.
  • You have selected no valid headers and methods (verbs). You either need to use specific values here, or * (which probably makes more sense if you are applying this globally).

eg you want the following:

var cors = new EnableCorsAttribute("http://srv02:2300", "*", "*");
config.EnableCors(cors);

this should instruct browsers (using the OPTIONS response) that if they want to call this API from http://srv02:2300/* with any verbs or headers, its ok. If another domain tries to call this API it will not be ok.