How To Enable Cross-Origin Requests (CORS) In ASP.NET Core

A web page cannot make requests to a different place than the one that served it thanks to browser security. The same-origin arrangement is the name given to this restriction. The same-origin configuration prevents a malicious location from reading sensitive data from another location. You might occasionally want to allow your app to receive cross-origin requests from other locations.

Same origin

These two URLs have the same origin:

  • https://test.com/goo.html
  • https://test.com/hoo.html

These URLs have different origins than the previous two URLs:

  • https://test.net: Different domain
  • https://www.test.com/koo.html: Different subdomain
  • http://test.com/soo.html: Different scheme
  • https://test.com:9000/voo.html: Different port

CORS with named policy and middleware

var SpecifiedOrigins = "SpecifiedOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options => {
    options.AddPolicy(name: SpecifiedOrigins, policy => {
        policy.WithOrigins("http://test1.com", "http://www.test2.com");
    });
});
app.UseCors(SpecifiedOrigins);

CORS with default policy and middleware

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options => {
    options.AddDefaultPolicy(policy => {
        policy.WithOrigins("http://test1.com", "http://www.test2.com");
    });
});
app.UseCors();

Enable Cors with endpoint routing

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options => {
    options.AddPolicy(name: MyAllowSpecificOrigins, policy => {
        policy.WithOrigins("http://test1.com", "http://www.test2.com");
    });
});
app.UseCors();
app.UseEndpoints(endpoints => {
    endpoints.MapGet("/test", context => context.Response.WriteAsync("test")).RequireCors(MyAllowSpecificOrigins);
    endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
});

Enable CORS with attributes

// GET api/values
[EnableCors("Policy1")]
[HttpGet]
public ActionResult < IEnumerable < string >> Get() Get() {
        return new string[] {
            "Go",
            "Run"
        };
    }
    [EnableCors("Policy2")]
    [HttpGet("{id}")]
public ActionResult < string > Get(int id) {
    return id
    switch {
        1 => "Test1",
            2 => "Test2",
            _ => NotFound(),
    };
}
builder.Services.AddCors(options => {
    options.AddPolicy("Policy1", policy => {
        policy.WithOrigins("http://test1.com", "http://www.test2.com");
    });
    options.AddPolicy("AnotherPolicy", policy => {
        policy.WithOrigins("http://www.test3.com").AllowAnyHeader().AllowAnyMethod();
    });
});
app.UseCors();

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories