Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web API.

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.

STEP 1 – Create ASP.NET WebAPI 2 Application

I will be using Visual Studio 2013 as my development environment. Our first step will be to create an ASP.NET Web Application project based on the Web API template.

  • Open Visual Studio 2013 and create a new project of type ASP.NET Web Application.
  • On this project I create a solution called WebAPI.

  • Press OK, and a new screen will appear, with several options of template to use on our project.
  • Select the option WebAPI.

  • The solution will be created.

STEP 2 – Install Nuget

Now in order to use CORS we need to install a Nuget package.

So on the Visual Studio 2013, select the follow menu option:

Tools-> Library Package manager -> Manage NuGet Packages for Solution

Search for CORS and select the option Install.

This option, will install automatically the Nuget Package.

STEP 3 – Enable CORS on solution

Once all the “ingredients” are ready, it’s time to enable CORS.

C#
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Http; 
 
namespace WebApi2 
{ 
    public static class WebApiConfig 
    { 
        public static void Register(HttpConfiguration config) 
        { 
            // Web API configuration and services 
            config.EnableCors(); 
             
            // Web API routes 
            config.MapHttpAttributeRoutes(); 
 
            config.Routes.MapHttpRoute( 
                name: "DefaultApi", 
                routeTemplate: "api/{controller}/{id}", 
                defaults: new { id = RouteParameter.Optional } 
            ); 
        } 
    } 
} 
 Next, add the [EnableCors] attribute to the Controller class,  as follows
C#
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 
using System.Web.Http.Cors; 
 
namespace WebApi2.Controllers 
{ 
    [EnableCors(origins: "http://localhost:53029", headers: "*", methods: "*")] 
    public class TestController : ApiController 
    { 
        public string Get() 
        { 
            return "This is my controller response"; 
        } 
    } 
} 
 For enable CORS for the entire We Api project you could to this:

C#
public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
        var cors = new EnableCorsAttribute("http://localhost:53029""*""*"); 
        config.EnableCors(cors); 
    } 
}

STEP 4 – Make call from client

At this time, the server is ready, it’s time to work client side.

HTML
@{ 
    ViewBag.Title = "Home Page"; 
} 
 
<div class="jumbotron"    <h2>CORS (Cross-origin resource sharing)</h2> 
    <p class="lead"        <a href="#" class="btn btn-primary btn-large" id="testButton">Test CORS&raquo;</a> 
    </p> 
    <p    <p id="response"        NoResponse 
    </p> 
</div> 
 
 
@section scripts { 
    <script        var response = $('#response'); 
        $('#testButton') 
            .click(function () { 
                $.ajax({ 
                    type: 'GET', 
                    url: 'http://localhost:51277/api/test' 
                }).done(function (data) { 
                    response.html(data); 
                }).error(function (jqXHR, textStatus, errorThrown) { 
                    response.html(jqXHR.responseText || textStatus); 
                }); 
            }); 
    </script> 
}

Press the button, and check the request result to webapi from client side.

Resources

Some good resources about Windows Azure could be found here: