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

Browser security keeps a web page from making demands to a distinctive space from the one that served the net page. This confinement is called the same-origin arrangement. The same-origin arrangement anticipates a pernicious location from perusing delicate information from another location. Sometimes, you might want to permit other destinations to form cross-origin demands to your app.

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();