ElConrado
ElConrado

Reputation: 1640

How to enable CORS in ASP.net Core WebAPI with deafult and own policy

I would like to enable by EnableCors attribute my own "MyPolicy" for one controller and for the others I would like to use default policy. So in my configure services method I write

services.AddCors(options =>
{
    options.AddPolicy(name: "MyPolicy",
        builder => builder
            .WithOrigins("http://localhost:3000")
            .AllowCredentials()
            .AllowAnyMethod()
            .AllowAnyHeader());

    options.AddDefaultPolicy(
            builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
});

and than in Configure method I just call:

app.UseCors();

it does not work as I expected. It's only define DefaultPolicy and the only way to use "MyPolicy" is to use them as:

app.UseCors("MyPolicy");

But in this case default policy does not work. Is it possible to define own policies by AddPolicy and default policy by AddDefaultPolicy.

Upvotes: 1

Views: 2046

Answers (1)

ElConrado
ElConrado

Reputation: 1640

If you would like to use many own policies and default policy the solution is to define in configureservices:

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

        options.AddPolicy("AnotherPolicy",
            builder =>
            {
                builder.WithOrigins("http://www.contoso.com")
                                    .AllowAnyHeader()
                                    .AllowAnyMethod();
            });

    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

and use policies through EnableCorsAttribute like this:

  // GET api/values
    [EnableCors("AnotherPolicy")]
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "green widget", "red widget" };
    }

. In this case do not call UseCors method of app IApplicationBuilder object in configure method startup class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }
    //Do not use this method:
    //app.UseCors();

    app.UseHttpsRedirection();
    app.UseMvc();
}

Upvotes: 5

Related Questions