-1

I am enabling cors between two sites. I have enabled the cors in global.asax.cs.

Still I am facing problems

No 'Access-Control-Allow-Origin' header is present on the requested resource

When I added in my web.config:

<customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
    <add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept" />
</customHeaders>

Then I am getting error - only one header is allow no multiple header allow.

Request Header

Access-control-request-headrs : authorization , content-type
Access-control-request-method :GET
Origin- xyz.com

Response Header
Allow:OPTIONS,TRACE,GET,HEAD,POST
CONTENT-LENGHT :0

GENERAL
REQUEST URL: ABC.COM
RQUEST METHOD : OPTIONS
STATUS CODE:200 OK
aynber
  • 22,380
  • 8
  • 50
  • 63
  • Add your C# code or Jquery Code which you have specified the URL to call another site. – Laxman Gite Aug 02 '19 at 07:15
  • $.ajax({ url: url, type: 'GET', withCredentials: true, headers: { 'Authorization': authString, }, dataType: 'json', success: function (response) {} – Shakeeb Ahmad Aug 02 '19 at 07:33
  • $.ajax({ url: url, type: 'GET', withCredentials: true, headers: { 'Authorization': authString, }, dataType: 'json', crossDomain:true, success: function (response) {} – Laxman Gite Aug 02 '19 at 08:06
  • add *crossDomain:true* in your ajax call and then verify. – Laxman Gite Aug 02 '19 at 08:07

1 Answers1

-1

You have forgotten to add OPTIONS to the list of allowed methods:

<customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, OPTIONS, DELETE, HEAD" />
    <add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept" />
</customHeaders>

Would be the correct configuration of headers to allow CORS requests.
Your browser cannot see what methods are allowed on that endpoint since it's OPTIONS request is being denied.
This MDN article about preflight contains more information.

I would also recommend using the new Fetch API to make web api calls. Here is an example:

fetch('example.com/apiendpoint', {
    mode: 'cors',
    credentials: 'include',
    headers: { 'Authorization': authString }
}).then(
    response => response.json()
); // parses JSON response into native JavaScript objects 

A side note, your example CORS headers specify all origins, but it would be wise to only include the origins you expect to be making these requests. Also, to use CORS on a per action / controller basis instead of site wide.

Serdalis
  • 10,296
  • 2
  • 38
  • 58