Sagar Chaudhary Sagar Chaudhary - 17 days ago 8
ASP.NET (C#) Question

I am migrating my asp.net web api to asp.net core. Cors migration

In my asp.net project i have defined cors in webapiconfig file like this

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
var cors = new EnableCorsAttribute("*", "*", "*", "DataServiceVersion, MaxDataServiceVersion") { SupportsCredentials = true };
config.EnableCors(cors);


Now I want to migrate it to asp.net core. How can it be done? Please help.

Answer
  1. Add the CORS services:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddPolicy("AllowAll", builder =>
        {
            builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin()
                .AllowCredentials()
                .WithExposedHeaders("DataServiceVersion", "MaxDataServiceVersion");
        }));
    }
    
  2. Use the CORS middleware:

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("AllowAll");
    } 
    
Comments