CORS on ASP.NET

http://enable-cors.org/server_aspnet.html

 

CORS on ASP.NET
If you don’t have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:

Response.AppendHeader(“Access-Control-Allow-Origin”, “*”);
Note: this approach is compatible with IIS6, IIS7 Classic Mode, and IIS7 Integrated Mode.

ASP.NET Web API
ASP.NET Web API 2 supports CORS.

To enable CORS support, add the Microsoft.AspNet.WebApi.Cors NuGet package to your project.

Add this code to your configuration:

public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
}
To enable cross-origin requests, add the [EnableCors] attribute to your Web API controller or controller method:

[EnableCors(origins: “http://example.com”, headers: “*”, methods: “*”)]
public class TestController : ApiController
{
// Controller methods not shown…
}
Enabling Globally
The method described above can also be used to enable CORS across the API without annotating each controller:

public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute(“http://example.com”, “*”, “*”);
config.EnableCors(corsAttr);
}
For more information, see the official Web API documentation.

Libraries
The open source Thinktecture.IdentityModel security library contains a full-featured CORS implementation. Here is the announcement page with some samples. Here is the source for .NET 4.5 and for .NET 4.0. Both are packaged into a Nuget package downloadable from Visual Studio.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s