ASP.NET Core CORS安装程序因多个主机而失败

时间:2019-02-26 08:58:16

标签: c# asp.net-core cors

这是已知错误还是我们设置不正确?

版本1

    public static IServiceCollection AddAndConfigureCors(this IServiceCollection services,
        ILogger logger,
        params string[] allowedCorsOrigins)
    {
        logger.LogDebug("Starting CORS Configuration.");
        logger.LogDebug("Configuring CORS.");
        var corsBuilder = new CorsPolicyBuilder()
            .AllowAnyHeader()
            .AllowAnyMethod()
            .WithHeaders()
            .AllowCredentials();

        if (allowedCorsOrigins.Contains("*"))
            corsBuilder.AllowAnyOrigin();
        else
            corsBuilder.WithOrigins(allowedCorsOrigins);


        services.AddCors(options => { options.AddPolicy(CoreConstants.Policies.SiteCors, corsBuilder.Build()); });
        logger.LogDebug("Enabled Cross Origin: {AllowedOrigins}", string.Join(",", allowedCorsOrigins));
        logger.LogDebug("Completed CORS Configuration.");
        return services;
    }

版本2

public static class CorsConfiguration
{
    public static IServiceCollection AddAndConfigureCors(this IServiceCollection services,
        ILogger logger,
        params string[] allowedCorsOrigins)
    {
        logger.LogDebug("Starting CORS Configuration.");
        logger.LogDebug("Configuring CORS.");
        var corsBuilder = new CorsPolicyBuilder()
            .AllowAnyHeader()
            .AllowAnyMethod()
            .WithHeaders()
            .AllowCredentials();

        CorsPolicy corsPolicy;

        if (allowedCorsOrigins.Contains("*"))
        {
            corsBuilder.AllowAnyOrigin();
            corsPolicy = corsBuilder.Build();
        }
        else
        {
            corsPolicy = corsBuilder.Build();
            foreach(var origin in allowedCorsOrigins)
                corsPolicy.Origins.Add(origin);
        }


        services.AddCors(options => { options.AddPolicy(CoreConstants.Policies.SiteCors, corsPolicy); });
        logger.LogDebug("Enabled Cross Origin: {AllowedOrigins}", string.Join(",", allowedCorsOrigins));
        logger.LogDebug("Completed CORS Configuration.");
        return services;
    }

当我们致电services.AddAndConfigureCors(logger, "*")时,一切都会按预期运行。

当我们致电services.AddAndConfigureCors(logger, _config["AllowedHosts"].Split(',')时,我们收到一个错误请求-无效的主机名

arrayOfHosts只是一个来自appsettings的字符串数组,看起来像这样:"AllowedHosts": "http://localhost:5000,https://localhost:5001"这被拆分为string []。

Console Browser Debug of Startup.cs

0 个答案:

没有答案