Raviteja
Raviteja

Reputation: 257

How to enable cors in .Net Core for web api ajax call

Am trying pull data from .net core web api using ajax call am getting the below error

Failed to load http://localhost:8085/api/menu: Response for preflight has invalid HTTP status code 404.

but am getting data sucessfully from postman.

am trying below code for ajax

$(document).ready(function(){
  $.ajax({ 
    url: 'http:/localhost:8085/api/menu', 
    type: 'GET', 
    dataType: 'json',
    data: '{ }',
    success: function (data) { 
        console.log(data); 
    },
    failure: function (data) {  
        alert(data.responseText);  
    }, //End of AJAX failure function  
    error: function (data) {  
        alert(data.responseText);  
    } 
  });
});

I have added below tag in web.config file

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

Please suggest your thoughts. Thanx in advance.

Upvotes: 0

Views: 977

Answers (1)

djaszczurowski
djaszczurowski

Reputation: 4533

you can define your policy in Startup file as a part of ConfigureServices method

for example:

{
  services.AddCors(c => {
      c.AddPolicy("policyName", p => {
          p.AllowAnyOrigin().AllowAnyMethod();
      });
  });
}

and then in Configure method

app.UseCors("policyName");

Upvotes: 4

Related Questions