Click here to Skip to main content
15,881,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i am getting the CORS issue while accessing the deployed ASP.Net Web API 2 while running the angular app locallly.

the same API is working with postman.


Error:
Access to XMLHttpRequest at 'https://someserver.com/someservice/api/like/Getlikedetails' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


What I have tried:

i have already enabled the all cors policy in api.

in WebApiConfig.cs file

config.EnableCors(new EnableCorsAttribute("*", headers: "*", methods: "*"));
            config.MapHttpAttributeRoutes();
Posted
Updated 5-Nov-20 4:21am

1 solution

Either you haven't deployed the CORS-enabled version to the server, or the API you've updated isn't the API you're calling.

Use your browser's developer tools to inspect the network request, and look at the response headers to check the Access-Control-Allow-Origin header.

Cross-Origin Resource Sharing (CORS) - HTTP | MDN[^]

NB: The request works from Postman because it's not running within a browser, and is not subject to the cross-site request limits imposed on web applications.
 
Share this answer
 
Comments
Virendra S from Bangalore, Karnataka 16-Dec-20 11:52am    
only the token api is getting cors issue, other endpoints are working fine.

[HttpPost]
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{ //Do some claims stuff}
Richard Deeming 16-Dec-20 11:55am    
Then your token API is not returning the correct CORS headers.

This isn't rocket science. If a request is blocked because it's not returning the correct CORS headers, then it's not returning the correct CORS headers.

And take another look at your question. Where precisely have you mentioned the "token API" and the "other endpoints"?
Virendra S from Bangalore, Karnataka 16-Dec-20 11:53am    
protected void Application_BeginRequest(object sender,EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
if(HttpContext.Current.Request.HttpMethod=="OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
HttpContext.Current.Response.End();
}
}

this is my global.axax.cs file method
Richard Deeming 16-Dec-20 11:56am    
That's nothing like the code you posted in your question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900