ASP.NET Core Web API Cors Error [SOLVED]
By Henri Parviainen
Today I struggled hours with a simple cors error while building ASP.NET Core Web API with a React client app.
I wasn't able to find a working solution to this problem on Stackoverflow or Google.
So..
When I finally was able to fix the error, I naturally wanted to share it with the world.
In my case, there were actually two different cors errors and I will show you what fixed them for me.
I am not saying that these solutions are universal and will fix all of your cors errors, but they might help someone who is in the same situation where I was.
Error 1: No 'Access-Control-Allow-Origin' header
Access to XMLHttpRequest at 'http://localhost:1554/api/route/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Solution - use https instead of http
Change requested url from:
http://localhost:1554/api/route/
to
https://localhost:44300/api/route/
.
Please keep in mind that your port numbers might be different than mine.
You can find the right SSL port from Properties/launchSettings.json
in your ASP.NET Web API project solution.
So, if you were using HTTP before, this should fix the No 'Access-Control-Allow-Origin' header error.
However, you might still get another error after this. Like I did.
Error 2: preflight request doesn't pass
Access to XMLHttpRequest at 'https://localhost:44300/api/route/' from origin 'http://localhost:3000' 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.
Now, this might look like a very similar error to the previous one but it's actually different. And there is a different fix as well.
Solution - remove headers or change Content-Type
The keyword to spot on the error message is preflight request
.
A preflight request is a HTTP OPTIONS request the browser sends to our server before the actual request to check if the CORS protocol is understood and a server is aware of using specific methods and headers.
To fix this error, we have two options.
- Eighter we handle the preflight request on our server and return HTTP status code 200, so that the browser knows it's okay to proceed sending the actual request.
- Or we can modify our actual request so that the preflight doesn't get flagged and send at all.
We will proceed with the latter.
The preflight will be sent if:
I. You have custom request headers other than Accept
, Accept-Language
, Content-Language
, Content-Type
, DPR
, Downlink
, Save-Data
, Viewport-Width
, or Width
II. You have Content-Type
header with any other value than application/x-www-form-urlencoded
, multipart/form-data
or text/plain
.
The solution is removing these headers and changing the Content-Type.
Hopefully, this post will help someone who is struggling with this.
Thanks for reading!