【问题标题】:How to enable CORS in Asp.Net Core 3.0 WebAPI如何在 Asp.Net Core 3.0 WebAPI 中启用 CORS
【发布时间】:2020-09-07 21:49:39
【问题描述】:

我想通过 Asp.Net Core 3.0 API 项目启用 CORS。这是生成的基本 Asp.Net Core Api 模板。模板中的所有内容都是默认设置,除了我从文档中添加了 CORS 设置

public class Startup
 {
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddCors(opt =>
        {
            var origins = Configuration
                .GetSection("AllowedHosts")
                .Get<string[]>();

            opt.AddPolicy("CorsPolicy", builder => builder
                    .WithOrigins(origins)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .Build());
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("CorsPolicy");
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

我应该如何设置才能在 .net core web api 中获取正确的 CORS? 允许的主机是:

【问题讨论】:

  • 对我来说似乎是对的,那代码有什么问题?
  • 是的,它看起来是正确的,你能指定更多你想要实现的目标吗?
  • 我从另一个应用程序调用它时遇到异常Access to XMLHttpRequest at 'http://localhost:44314/api/Reservation' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • @devcrp 如果我将其更改为 services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader( ) .AllowCredentials()); });
  • 我也可以从应用设置中获取值“localhost:4200”、“localhost:44349”吗?

标签: c# rest asp.net-core cors cross-domain


【解决方案1】:

Cors 的优先顺序应该在添加控制器之前。应按照官方文档中的定义添加:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

按照此代码:

public class Startup
 {
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {            
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.WithOrigins("http://localhost:4200", "http://localhost:44349")
                .AllowAnyMethod()
                .AllowAnyHeader();
                //.AllowCredentials());
        });

      services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();    
        app.UseRouting(); 

        app.UseCors("CorsPolicy");   
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

根据official documentation,必须注意的是:

指定 AllowAnyOrigin 和 AllowCredentials 是不安全的 配置,并可能导致跨站点请求伪造。 CORS 配置应用时服务返回无效的 CORS 响应 两种方法都可以。

【讨论】:

  • 我也可以从应用设置中获取值“localhost:4200”、“localhost:44349”吗?
  • 是的,在 app.settings 中放入逗号分隔的字符串,稍后再检索。
  • 我只是将“AllowedHosts”:[“localhost:4200”],在应用程序设置中,如下所示,但没有工作 services.AddCors(opt => { var origins = Configuration . GetSection("AllowedHosts") .Get(); opt.AddPolicy("CorsPolicy", builder => builder .WithOrigins(origins) .AllowAnyMethod() .AllowAnyHeader() .Build()); });
猜你喜欢
  • 2021-12-30
  • 2021-04-09
  • 2015-11-03
  • 2020-09-02
  • 1970-01-01
  • 2017-07-14
  • 2020-09-21
  • 2021-10-23
相关资源
最近更新 更多