How to enable CORS in ASP.NET Core

前端 未结 12 682
无人及你
无人及你 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:46

    Got this working with .Net Core 3.1 as follows

    1.Make sure you place the UseCors code between app.UseRouting(); and app.UseAuthentication();

            app.UseHttpsRedirection();
    
            app.UseRouting();
            app.UseCors("CorsApi");
    
            app.UseAuthentication();
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
            });
    

    2.Then place this code in the ConfigureServices method

    services.AddCors(options =>
            {
                options.AddPolicy("CorsApi",
                    builder => builder.WithOrigins("http://localhost:4200", "http://mywebsite.com")
                .AllowAnyHeader()
                .AllowAnyMethod());
            });
    

    3.And above the base controller I placed this

    [EnableCors("CorsApi")]
    [Route("api/[controller]")]
    [ApiController]
    public class BaseController : ControllerBase
    

    Now all my controllers will inherit from the BaseController and will have CORS enabled

提交回复
热议问题