Home > Back-end >  Enable CORS for any port on localhost as well as for the list of specific domains
Enable CORS for any port on localhost as well as for the list of specific domains

Time:08-24

In ASP.Net core 6.0, I want to enable CORS for localhost as well as for the list of specific domains

I have implemented something like this

public class Startup
{
    private readonly string nondevCORSPolicyName = "NonDevCorsPolicy";
    private readonly string devCORSPolicyName = "DevCorsPolicy";

    public void ConfigureServices(IServiceCollection services)
    {       
        ....
        services.AddCors(opt =>
        {
            opt.AddPolicy(name: this.nondevCORSPolicyName, builder =>
            {
                builder.WithOrigins("https://*.companydomain.com")
                    .SetIsOriginAllowedToAllowWildcardSubdomains();
            });
        });

        services.AddCors(opt =>
        {
            opt.AddPolicy(name: this.devCORSPolicyName, builder =>
            {
                builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
            });
        });
        ....
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseCors();
        .....
    }
}

Does it work?

CodePudding user response:

I was able to achieve this as highlighted below

// CORS Policies
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(builder =>
    {
        builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost" || new Uri(origin).Host == "myweb.local");
    });
});


// Enable Cors
app.UseCors();
  • Related