How to enable CORS in ASP.NET Core

前端 未结 12 657
无人及你
无人及你 2020-11-22 14:11

I am trying to enable cross origin resources sharing on my ASP.NET Core Web API, but I am stuck.

The EnableCors attribute accepts policyName

12条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 14:36

    You have to configure a CORS policy at application startup in the ConfigureServices method:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));
    
        // ...
    }
    

    The CorsPolicyBuilder in builder allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:

    [EnableCors("MyPolicy")]
    

    Or apply it to every request:

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("MyPolicy");
    
        // ...
    
        // This should always be called last to ensure that
        // middleware is registered in the correct order.
        app.UseMvc();
    }
    

提交回复
热议问题