How to enable CORS in ASP.NET Core

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

    All the workaround mentioned above may work or may not work, in most cases it will not work. I have given the solution here

    Currently I am working on Angular and Web API(.net Core) and came across CORS issue explained below

    The solution provided above will always work. With 'OPTIONS' request it is really necessary to enable 'Anonymous Authentication'. With the solution mentioned here you don't have to do all the steps mentioned above, like IIS settings.

    Anyways someone marked my above post as duplicate with this post, but I can see that this post is only to enable CORS in ASP.net Core, but my post is related to, Enabling and implementing CORS in ASP.net Core and Angular.

    0 讨论(0)
  • 2020-11-22 14:39

    If you are hosting on IIS, one possible reason is you are getting this is because IIS is blocking OPTIONS verb. I spent almost an hour because of this:

    One telltale indication is you are getting 404 error during OPTIONS request.

    To fix this, you need to explicitly tell IIS not to block OPTIONS request.

    Go to Request Filtering:

    Make sure OPTIONS is allowed:

    Or, just create a web.config with the following setting:

    <system.webServer>
        <security>
            <requestFiltering>
                <verbs>
                    <remove verb="OPTIONS" />
                    <add verb="OPTIONS" allowed="true" />
                </verbs>
            </requestFiltering>
        </security>
    </system.webServer>
    
    0 讨论(0)
  • 2020-11-22 14:43

    you have three ways to enable CORS:

    • In middleware using a named policy or default policy.
    • Using endpoint routing.
    • With the [EnableCors] attribute.

    Enable CORS with named policy:

    public class Startup
    {
        readonly string CorsPolicy = "_corsPolicy";
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(name: CorsPolicy,
                                  builder =>
                                  {
                                     builder.AllowAnyOrigin()
                                          .AllowAnyMethod()
                                          .AllowAnyHeader()
                                          .AllowCredentials();
                                  });
            });
    
            // services.AddResponseCaching();
            services.AddControllers();
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
    
            app.UseCors(CorsPolicy);
    
            // app.UseResponseCaching();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
    

    UseCors must be called before UseResponseCaching when using UseResponseCaching.

    Enable CORS with default policy:

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                    {
                         builder.AllowAnyOrigin()
                                          .AllowAnyMethod()
                                          .AllowAnyHeader()
                                          .AllowCredentials();
                    });
            });
    
            services.AddControllers();
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
    
            app.UseCors();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
    

    Enable CORS with endpoint

    public class Startup
    {
        readonly string CorsPolicy = "_corsPolicy ";
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(name: CorsPolicy,
                                  builder =>
                                  {
                                      builder.AllowAnyOrigin()
                                          .AllowAnyMethod()
                                          .AllowAnyHeader()
                                          .AllowCredentials();
                                  });
            });
    
            services.AddControllers();
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
    
            app.UseCors();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers()
                         .RequireCors(CorsPolicy)
            });
        }
    }
    

    Enable CORS with attributes

    you have tow option

    • [EnableCors] specifies the default policy.
    • [EnableCors("{Policy String}")] specifies a named policy.
    0 讨论(0)
  • 2020-11-22 14:44

    Step 1: We need Microsoft.AspNetCore.Cors package in our project. For installing go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution. Search for Microsoft.AspNetCore.Cors and install the package.

    Step 2: We need to inject CORS into the container so that it can be used by the application. In Startup.cs class, let’s go to the ConfigureServices method and register CORS.

    So, in our server app, let’s go to Controllers -> HomeController.cs and add the EnableCors decorator to the Index method (Or your specific controller and action):

    For More Detail Click Here

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题