Enable CORS in web api

CORS support in Web API

If you read the Web API tutorials from docs.microsoft.com, all of them are teaching you to create the server app (Web API) and the client app in the same solution. In fact, we usually separate the server and client application into separate applications. You will then find out the client application cannot call any Web API method in the server application. It is because of the CORS.

What is CORS?

CORS stands for Cross-Origin Resource Sharing. CORS is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP. This tutorial shows how to enable CORS in your Web API application.

If your application is ASP.NET Web API 2, now you could do the following to enable CORS

  • Install Microsoft.AspNet.WebApi.Cors from Nuget
  • Open file App_Start/WebApiConfig.cs. In Register method, add this code config.EnableCors();
  • You can then add “[EnableCors(origins: “https://localhost:8081”, headers: “*”, methods: “*”)]” to any method that you want to enable CORS
  • You could also add the following into Web.config, so that CORS will be enabled to all methods
  <!-- Allow Web API to be called from a different domain. --> 
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="*" />

This is how you can enable CORS on your web api application.

Thanks for dropping by !! Feel free to comment to this post or you can drop an email at [email protected]