there are 100s of question on CORS on web-api, and on how to enable CORS, there is a different answer each one provides. I am so confused and dont know which answer is correct. And the problem is none of the answers actually explains it point wise, what each line of code does, so that I can understand and solve my problem rather than copy-pasting the code.
anyways, the question is: I am using asp.net web api 2 using owin. And i need to enable CORS. how do I do it? There is cors settings for OWIN
application.UseCors(CorsOptions.AllowAll);
and there is cors settings for asp.net web api
var cors = new EnableCorsAttribute("*", "*", "*", "*");
config.EnableCors(cors);
which one should I use given I am not using OAUTH (I am specifying this because answers on SO differ on when we use OAUTH v/s when we dont use it).
Do i need to enable CORS for both OWIN & WEB-API or only for one of them. There is issue if both are enabled, read here
It would be really helpful if someone can explain me the difference between
- OWIN CORS
- WEB API CORS
- CORS with OAUTH using OWIN/WEBAPI
Also there are answers for self-hosted web api against owin hosted web-api, which further adds to the confution :(, sorry for the rant
There is a way to fix this. Since OWIN and ASP.NET.CORS libraries are working simultaneously. Owin token or authentication method needs to be configured to enable CORS separately from all other API controllers.
Fist thing first, don't use cors with Owin in Startup.cs :
Find GrantResourceOwnerCredentials method and add Access-Control-Allow-Origin to context so when it returns a call after authentication is completed that browser finds the header and accepts it.
Now install Microsoft.AspNet.WebApi.Cors package from Nuget to your webapi project, and add this to Register method
Worked for me.
You are supposed to use
Web API's CORS
if you need CORS applied to your API Controllers. For everything else (like a token service) you're stuck with having to useOwin.Cors
.If you end up using both, you'll need to make sure they don't overlap and apply CORS twice to the same request.
Web API 2.2
makes it easy to enable CORS by providing theEnableCorsAttribute
.Basic Usage
Attribute definition
To enable CORS globally use
You will also need to install the CORS package from nuget