【问题标题】:CORS error keep happening even after enabling it, with .NET Core and Angular Client使用 .NET Core 和 Angular 客户端启用 CORS 错误后,它仍然会发生
【发布时间】:2020-05-22 06:59:12
【问题描述】:

我有 .net Core 3.0 Web API 项目,我在其中启用了给定的 CORS:

配置服务

services.AddCors(options =>
{
  options.AddPolicy("AllowOrigin", builder => builder.AllowAnyOrigin());
});

在配置方法中

app.UseCors();

当我使用 Angular 应用程序中的 httpclient 调用此端点时,我会收到 CORS 错误。

我可以看到标题如下:

我认为在我的启动中添加 CORS 应该可以解决这个问题。

更新:

添加配置和配置服务代码:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddDbContext<LabSoftwareContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LabDatabase")));

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "Lab API",
                Description = "Lab Software APIs"
            });
        });

        services.Configure<IISServerOptions>(options =>
        {
            options.AutomaticAuthentication = false;
        });

        services.AddCors(options =>
        {
            options.AddPolicy("AllowOrigin", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
        });
    }


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors("AllowOrigin");

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

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

        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Lab Software API");
        });
    }

【问题讨论】:

  • 你能在 Startup.cs 中显示你的 Configure() 方法代码吗?
  • @Bob 更新了问题:使用 .net Core 3.0

标签: angular asp.net-core cors


【解决方案1】:

我认为这是您的中间件在Configure() 中的顺序 - 如果顺序不正确,可能会导致意外的 Cors 故障。

例如我认为UseCors()可能需要放在UseHttpsRedirection()之后

这里有一个(复杂的!)表格解释了中间件的顺序:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1#built-in-middleware

您的代码根据同一页面中的示例进行了修改:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    app.UseRouting();
    app.UseCors();

    app.UseAuthentication();
    app.UseAuthorization();

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

    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Lab Software API");
    });
}

【讨论】:

    【解决方案2】:
    [EnableCors("your_policy")]
    public class BaseController : apiController
    

    对我有用的一件事是,尽管使用了 Configure 方法,但我需要在控制器中指定 CORS。

    【讨论】:

    • 不幸的是,这并没有帮助:只要我添加,我就会收到此错误:
    • System.InvalidOperationException: Endpoint LabSoftware.Controllers.UserMasterController.GetUserMaster (LabSoftware) 包含 CORS 元数据,但未找到支持 CORS 的中间件。通过在应用程序启动代码中对 Configure(..) 的调用中添加 app.UseCors() 来配置应用程序启动。
    • 您是否使用app.UserCors() 并为策略定义名称?如果没有,那么您有默认策略,然后使用 [EnableCors] 不带任何参数
    【解决方案3】:

    将这些写在配置方法的末尾

    app.UseCors(x=>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseAuthentication();app.UseMvc();
    

    也将 https 更改为 http

    【讨论】:

    • 没有运气,仍然出现此错误:Access to XMLHttpRequest at 'https://localhost:44378/api/UserMaster/1' 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.
    • 不要使用 https 使用 http
    • 这是一个非常危险的建议 - 即使这不能说服您,一旦您发布您的应用程序,您会发现您的网站被 chrome 和 firefox 标记为不安全。
    猜你喜欢
    • 1970-01-01
    • 2018-12-23
    • 2019-01-09
    • 2019-03-03
    • 1970-01-01
    • 2021-01-01
    • 2020-06-22
    • 1970-01-01
    • 2016-03-21
    相关资源
    最近更新 更多