CORE3.1 add CORS support

Setting up CORS

To setup CORS for your application you use the Microsoft.AspNetCore.Cors package. In your 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(IServiceCollection services)
{
    services.AddCors();
}

Enabling CORS with middleware

To enable CORS for your entire application add the CORS middleware to your request pipeline using the UseCors extension method. Note that the CORS middleware must precede any defined endpoints in your app that you want to support cross-origin requests (ex. before any call to UseMvc).

You can specify a cross-origin policy when adding the CORS middleware using the CorsPolicyBuilder class. There are two ways to do this. The first is to call UseCors with a lambda:

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

The lambda takes a CorsPolicyBuilder object. I’ll describe all of the configuration options later in this topic. In this example, the policy allows cross-origin requests from “http://example.com” and no other origins.

Note that CorsPolicyBuilder has a fluent API, so you can chain method calls:

app.UseCors(builder =>
    builder.WithOrigins("http://example.com")
           .AllowAnyHeader()
    );

The second approach is to define one or more named CORS policies, and then select the policy by name at run time.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder => builder.WithOrigins("http://example.com"));
    });
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("AllowSpecificOrigin");
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

PS: app.UseCors() should be set between Routing and Endpoints

configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(…).

https://jakeydocs.readthedocs.io/en/latest/security/cors.html#setting-up-cors

Leave a Comment

Your email address will not be published.