Enabling CORS (Cross-Origin Requests) in your ASP.NET Web API 2 service


What is “Same Origin”?

Two URLs have the same origin if they have identical schemes, domain, subdomain, and ports. (RFC 6454)

Enable CORS in your Web API Service

1. Install-Package Microsoft.AspNet.WebApi.Cors

2. In WebApiConfig.cs ‘s WebApiConfig.Register method, add:


3. Add the [EnableCors] attribute to the Controller/Action:

[EnableCors(origins: “http://mywebclient.azurewebsites.net”, headers: “*”, methods: “*”)]
* Do not include a forward slash at the end of the origins URL.

How CORS Works

The CORS specification introduces several new HTTP headers that enable cross-origin requests. If a browser supports CORS, it sets the Origin header automatically for cross-origin request; you don’t need to do anything special in your JavaScript code. And the browser will inspect Access-Control-Allow-Origin header in the response to determine whether to return the response content to the caller or not.

Here is an example of a cross-origin request. The “Origin” header gives the domain of the site that is making the request.


GET http://myservice.azurewebsites.net/api/test HTTP/1.1
Accept: */*
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Host: myservice.azurewebsites.net


If the server allows the request, it sets the Access-Control-Allow-Origin header. The value of this header either matches the Origin header, or is the wildcard value “*”, meaning that any origin is allowed.

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/plain; charset=utf-8
Date: Wed, 05 Jun 2013 06:27:30 GMT
Content-Length: 17

GET: Test message

Reference: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s