在 ASP.Net Core 5 WebAPI 中启用 CORS

问题描述

与此问题相关的文章和问题数以百万计,但我找不到我的代码有什么问题。我有 StartupStartupProductionStartupDevelopment 如下。此外,我正在使用 ASP.Net Core 5,并且基于 documentation,我认为我这样做是正确的。

仅供参考,起初,我使用 AllowAnyOrigin 进行开发,但我也测试了 .WithOrigins("http://localhost:3000"),它运行良好。我的后端在开发中运行在 https://localhost:44353 下,在生产中运行在 https://api.example.com 下。

public class Startup
{
    protected const string CorsPolicyName = "CorsPolicyName";

    public virtual void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(
                    new System.Text.Json.Serialization.JsonStringEnumConverter());
            });

        services.AddABunchOfOtherServices();
    }

    public virtual void Configure(IApplicationBuilder app,IWebHostEnvironment env)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseCors(CorsPolicyName);
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseMiddleware<CheckUserConfirmedMiddleware>();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute
            (
                name: "default",pattern: "{controller=Home}/{action=Index}/{id?}"
            )
            .RequireCors(CorsPolicyName);
        });
    }
}

public class StartupProduction : Startup
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(
                CorsPolicyName,policy => policy
                    .WithOrigins("https://example.com","http://example.com")
                    //.WithOrigins(Configuration.GetValue<string>("AllowedHosts").Split(';').ToArray())
                    .AllowAnyMethod()
                    .AllowAnyHeader());
        });

        base.ConfigureServices(services);
    }

    public override void Configure(IApplicationBuilder app,IWebHostEnvironment env)
    {
        app.UseMiddleware(typeof(ErrorHandlingMiddleware));

        // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();

        base.Configure(app,env);
    }
}

public class StartupDevelopment : Startup
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
            options.AddPolicy(
                CorsPolicyName,policy =>
                    policy
                        //.AllowAnyOrigin()
                        .WithOrigins("http://localhost:3000")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
            )
        );

        base.ConfigureServices(services);

        services.AddSwaggerGen(....);
    }

    public override void Configure(IApplicationBuilder app,IWebHostEnvironment env)
    {
        app.UseMiddleware<DevelopmentErrorHandlingMiddleware>();

        base.Configure(app,env);

        app.UseSwagger();

        app.UseSwaggerUI(options =>
        {
            options.SwaggerEndpoint("swagger/v1/swagger.json","API v1");
            options.RoutePrefix = string.Empty;
        });
    }
}

我也试过 default policy

更新

我已在 Visual Studio 中将 Environment 设置为 Production 以对其进行调试,现在我在开发中遇到了同样的问题。

从源“http://localhost:3000”获取“https://localhost:44353/api/v1/User”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

临时解决方案

我注意到是 IIS 阻止了请求。它仅在我的 "AllowedHosts": "*", 中有 appsettings.json 时有效。因此,作为一种解决方法,我在我的 "MyRandomKey": "https://example.com", 中添加了 appsettings.json,并在我的 Startup 中使用了以下内容。

services.AddCors(options =>
                options.AddPolicy(
                    CorsPolicyName,policy =>
                        policy
                            .WithOrigins(Configuration.GetValue<string>("MyRandomKey").Split(";").ToArray())
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                )
            );

解决方法

AllowedHosts 和 CORS 不同。

AllowedHosts 用于主机过滤,因此即使您在应用程序中配置了 CORS 策略但不允许主机,IIS 也会拒绝该请求。

请参考此链接: Difference between AllowedHosts in appsettings.json and UseCors in .NET Core API 3.x

默认情况下它是 * 但您可以根据您的要求将其更改为。 在您的情况下,您可以设置“api.example.com”,或者如果您还想允许来自 localhost 则“api.example.com;localhost”。 设置后,IIS 将开始接受来自这些域的请求。

一旦 IIS 开始接受请求,您的应用程序级别配置的 CORS 策略将被应用和工作。 所以基本上 CORS 是允许访问您的 WebAPI 中的资源。

,

我认为没问题,而且,您可以从 DB 或 JSON 文件中获取来源。还, 你可以使用 ActionFilterAttribute 和这部分代码

    var csp = "default-src 'self' http://localhost:3000; object-src 'none'; frame-ancestors 'none'; sandbox allow-forms allow-same-origin allow-scripts; base-uri 'self';";

if (!context.HttpContext.Response.Headers.ContainsKey("Content-Security-Policy"))
{
    context.HttpContext.Response.Headers.Add("Content-Security-Policy",csp);
}

if (!context.HttpContext.Response.Headers.ContainsKey("X-Content-Security-Policy"))
{
    context.HttpContext.Response.Headers.Add("X-Content-Security-Policy",csp);
}
,

this doc about CORS preflight request,您可以找到以下信息:

CORS 预检请求用于确定请求的资源是否设置为由服务器跨源共享。并且 OPTIONS 请求始终是匿名的,如果未启用匿名身份验证,服务器将无法正确响应预检请求。

访问从源的“https://localhost:44353/api/v1/User”获取 'http://localhost:3000' 已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。如果不透明的响应满足您的需求,请设置请求的 模式为 'no-cors' 以在禁用 CORS 的情况下获取资源。

为了解决上述问题,如果您在本地运行应用程序以使用 CORS 进行测试,您可以尝试启用匿名身份验证。

此外,如果您的应用托管在 IIS 上,您可以尝试安装 IIS CORS module 并为应用配置 CORS。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...