ASP.net Core Cross-Origin Requests

Datetime:2016-08-22 22:07:04          Topic: ASP.NET           Share

In this article, we will learn:

  • What is Cross-Origin Request Sharing (CORS)?
  • How to set up CORS in ASP.net Core
  • Enable CORS for specific Action & Controllers in MVC
  • Enable CORS for all Requests in Middleware
  • Different CORS policy options
  • Summary

What is Cross-Origin Request Sharing (CORS)?

CORS is a mechanism that allows restricted resources on a web page to be requested from another domain(outside the domain) from which the resource originated.

For an example below 2 urls are from same origin:

http://csharpstar.com/test1

http://csharpstar.com/test2

Below URLs have different origins than the above two:

http://google.com – Different domain

http://csharpstar.com:1234/test1 – Different port

https://csharpstar.com/test1 – Different scheme

http://www.csharpstar.com/test1 – Different subdomain

How to set up CORS in ASP.net Core

You can use the Microsoft.AspNetCore.Cors package to setup CORS for your application.

In project.json file, add the following:

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

Add the CORS services in Startup.cs:

public void ConfigureServices(IServiceCollectionservices)
{
    services.AddCors();
}

Enabling CORS for specific Action & Controller in MVC

Per Action:

To specify a CORS policy for a action add the [EnableCors] attribute to the action.

public class TestController : Controller
{
    [EnableCors("AllowSpecificOrigin")] 
    public IActionResultIndex()
    {
        return View();
    }

Per Controller:

To specify a CORS policy for a controller add the [EnableCors] attribute to the action.

<pre>
public class TestController : Controller
{
    [EnableCors("AllowSpecificOrigin")] 

Globally: For all Controllers

You can enable CORS globally for all controllers by adding the CorsAuthorizationFilterFactory filter to the global filter collection:

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

Enabling CORS for all requests in Middleware

To enable CORS for your entire application add the CORS middleware to your request pipeline using the UseCors extension method.

You can enable CORS when adding the CORS middleware using CORSPolicyBuilder Class.You can do it in 2 ways.

1. UseCors with a Lambda:

public void Configure(IApplicationBuilderapp)
{
    app.UseCors(builder =>
        builder.WithOrigins("http://csharpstar.com"));
}

2. Define CORS policy and use by name at runtime:

public void ConfigureServices(IServiceCollectionservices)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder => builder.WithOrigins("http://csharpstar.com"));
    });
}
 
public void Configure(IApplicationBuilderapp)
{
    app.UseCors("AllowSpecificOrigin");
    app.Run(async (context) =>
    {
        awaitcontext.Response.WriteAsync("Hello World!");
    });
}

Different CORS policy options:

1. Set the allowed Origin:

//Allow one or more Origin
options.AddPolicy("AllowSpecificOrigins",
builder =>
{
    builder.WithOrigins("http://csharpstar.com", "http://www.google.com");
});
//Allow all Origin
options.AddPolicy("AllowAllOrigins",
    builder =>
    {
        builder.AllowAnyOrigin();
    });

2. Set the allowed HTTP Methods:

//Allow one or more specific HTTP methods
options.AddPolicy("AllowSpecificMethods",
    builder =>
    {
        builder.WithOrigins("http://csharpstar.com")
              .WithMethods("GET", "POST", "HEAD");
    });
//Allow all HTTP methods
ptions.AddPolicy("AllowAllMethods",
    builder =>
    {
        builder.WithOrigins("http://csharpstar.com")
              .AllowAnyMethod();
    });

3. Set the allowed Request Headers:

//To whitelist few headers
options.AddPolicy("AllowHeaders",
    builder =>
    {
        builder.WithOrigins("http://csharpstar.com")
              .WithHeaders("accept", "content-type", "origin", "x-custom-header");
    });
 
//To allow all headers
options.AddPolicy("AllowAllHeaders",
    builder =>
    {
        builder.WithOrigins("http://csharpstar.com")
              .AllowAnyHeader();
    });

4. Set the exposed response headers:

options.AddPolicy("ExposeResponseHeaders",
    builder =>
    {
        builder.WithOrigins("http://csharpstar.com")
              .WithExposedHeaders("x-custom-header");
    });

5. Cross Origin Request with Credentials:

options.AddPolicy("AllowCredentials",
    builder =>
    {
        builder.WithOrigins("http://csharpstar.com")
              .AllowCredentials();
    });

6. Set the preflight expiration time:

options.AddPolicy("SetPreflightExpiration",
    builder =>
    {
        builder.WithOrigins("http://csharpstar.com")
              .SetPreflightMaxAge(TimeSpan.FromSeconds(2520));
    });

You can read more on CORS and how it works here .

Summary:

In this article, we have discussed:

– What is CORS?

– How to set up CORS in ASP.net Core

– How to enable CORS in ASP.net Core

– Different CORS policy options

Thanks for Visiting !!

© 2016,admin. All rights reserved.





About List