How to enable CORS in ASP.NET Core

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

    Applies to .NET Core 1 and .Net Core 2 (further down)

    If using .Net-Core 1.1

    Unfortunately the docs are very confusing in this specific case. So I'll make it dead-simple:

    • Add Microsoft.AspNetCore.Cors nuget package to your project
    • In ConfigureServices method, add services.AddCors();
    • In Configure method, before calling app.UseMvc() and app.UseStaticFiles(), add:

      app.UseCors(builder => builder
          .AllowAnyOrigin()
          .AllowAnyMethod()
          .AllowAnyHeader()
          .AllowCredentials());
      

    That's it. Every client has access to your ASP.NET Core Website/API.


    If using .Net-Core 2.0

    • Add Microsoft.AspNetCore.Cors nuget package to your project
    • in ConfigureServices method, before calling services.AddMvc(), add:

       services.AddCors(options =>
          {
              options.AddPolicy("AllowAll",
                  builder =>
                  {
                      builder
                      .AllowAnyOrigin() 
                      .AllowAnyMethod()
                      .AllowAnyHeader()
                      .AllowCredentials();
                  });
          });
      
    • (Important) In Configure method, before calling app.UseMvc(), add app.UseCors("AllowAll");

      AllowAll is the policy name which we need to mention in app.UserCors. It could be any name.

提交回复
热议问题