Enable CORS in ASP.NET Web API

If you are developing Web API which you intend to call from other application or domains then you have to enable CORS (Cross Origin Resource Sharing) in your Web API project.

There are various ways of doing this

  • Enable CORS on Action
  • Enable CORS on Controller
  • Enable CORS globally
    • In WebApiConfig.cs
    • In Web.Config

We will see each of the above methods one by one but before that we have to do one common change for first two methods.

using System.Web.Http;

namespace DummyAPIApplication
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableCors();//Changed line in default WebApiConfig.Register method

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Other then this don’t forget to add reference to Systems.Web.Http.Cors and add same in your controller.

1. Enable CORS on Action

For enabling CORS on specific controller we have to simply add one attribute

public class DummyController : ApiController
{
    [EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
    public HttpResponseMessage GetData() 
    {
        //action code
    }
}

We can use wildcard like * for all three parameters origins, headers and methods of the attributes.

2. Enable CORS on Controller

For enabling CORS on complete controller use same attribute on controller and if there is a case where we want to enable CORS on complete controller but keep it disable on some of the action. For that you can use DisableCors attributes on action for which you want to keep CORS disable.

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace DummyAPIApplication.Controllers
{
    [EnableCors(origins: "https://example.com", headers: "*", methods: "*")]
    public class DummyController : ApiController
    {
        public HttpResponseMessage GetData()
	{
		//action code
	}

        [DisableCors]
        public HttpResponseMessage PostItem()
	{
		//action code
	}   
    }
}

3. Enable CORS Globally

For enabling CORS globally ther are two options as explained belwo

3.1 Enable CORS Globally in WebApiConfig.cs

This is straight and simple to implement

using System.Web.Http;

namespace DummyAPIApplication
{
	public static class WebApiConfig
	{
		public static void Register(HttpConfiguration config)
		{
			var cors = new EnableCorsAttribute("example.com", "*", "*");
			config.EnableCors(cors);
		}
	}
}

3.2 Enable CORS Globally in Web.Config

For doing the same as above through Web.Config instead of WebApiConfig.cs you have to do some modification in <system.webserver> tag of web config.

<system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <httpProtocol>
		<customHeaders>
			<add name="Access-Control-Allow-Origin" value="*" />
			<add name="Access-Control-Allow-Credentials" value="true"/>
			<add name="Access-Control-Allow-Headers" value="*" />
			<add name="Access-Control-Allow-Methods" value="*" />
		</customHeaders>
    </httpProtocol>
</system.webServer>

All these methods are simple enough even for any beginner in ASP.NET Web API.