Specifying a CORS Policy

By Mike Wasson

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 make cross-origin requests to your web app.

Cross Origin Resource Sharing 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. This topic shows how to enable CORS in your ASP.NET MVC 6 application. (For background on CORS, see How CORS works.)

Add the CORS package

In your project.json file, add the following:

  "dependencies": {
    "Microsoft.AspNet.Cors": "6.0.0-beta8"
  },

Configure CORS

To configure CORS, call AddCors in the ConfigureServices method of your Startup class, as shown here:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddCors(options =>
    {
        // Define one or more CORS policies
        options.AddPolicy("AllowSpecificOrigin",
            builder =>
            {
                builder.WithOrigins("http://example.com");
            });
    });
}

This example defines a CORS policy named “AllowSpecificOrigin” that allows cross-origin requests from “http://example.com” and no other origins. The lambda takes a CorsPolicyBuilder object. To learn more about the various CORS policy settings, see CORS policy options.

Apply CORS Policies

The next step is to apply the policies. You can apply a CORS policy per action, per controller, or globally for all controllers in your application.

Per action

Add the [EnableCors] attribute to the action. Specify the policy name.

public class HomeController : Controller
{
    [EnableCors("AllowSpecificOrigin")] 
    public IActionResult Index()
    {
        return View();
    }

Per controller

Add the [EnableCors] attribute to the controller class. Specify the policy name.

[EnableCors("AllowSpecificOrigin")]
public class HomeController : Controller
{

Globally

Add the CorsAuthorizationFilterFactory filter to the global filter collection:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
    });
}

The precedence order is: Action, controller, global. Action-level policies take precedence over controller-level policies, and controller-level policies take precedence over global policies.

Disable CORS

To disable CORS for a controller or action, use the [DisableCors] attribute.

    [DisableCors]
    public IActionResult About()
    {
        return View();
    }