Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Introduction
This article walks you through configuration of CORS on webapi.
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
Visual Studio 2013 is used as the 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.
http://code.msdn.microsoft.com/site/view/file/124188/1/1.png
- Press OK, and a new screen will appear, with several options of template to use on our project.
- Select the option WebAPI.
http://code.msdn.microsoft.com/site/view/file/124189/1/2.png
- The solution will be created.
STEP 2 - Install Nuget
In order to use CORS we need to install a Nuget package.
In 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.
http://code.msdn.microsoft.com/site/view/file/124191/1/3.png
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»</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>
}
http://code.msdn.microsoft.com/site/view/file/124192/1/4.png
Press the button, and check the request result to webapi from client side.
http://code.msdn.microsoft.com/site/view/file/124193/1/5.png
Resources
Some good resources about Windows Azure could be found here:
- My personal blog: http://joaoeduardosousa.wordpress.com/
- Download code: ASP.NET WebAPI - Enable Cors