简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM