从appsettings.json文件中读取原始URL会导致错误请求

问题描述 投票:0回答:1

当我在appsettings.Development.json文件中使用“allowedHosts”:“http://localhost:9000”,然后尝试检索Startup.cs中的值时,API会抛出“Bad request - Invalid hostname”异常

当使用“allowedHosts”:“*”时,一切正常,但也许它只是默认为任何原点,这就是它的工作原理。

appsettings.Development.json

{
    "app": {
    },
    "connectionStrings": {
        "mainDb": "Server=.\\SQLEXPRESS;Database=MailboxVisualizer;Trusted_Connection=True;"
    },
    "logging": {
        "logLevel": {
            "default": "Debug",
            "system": "Information",
            "microsoft": "Information"
        }
    },
    "allowedHosts": "http://localhost:9000"
}

Startup.cs

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; 

public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddMvcCore()
                .AddFormatterMappings()
                .AddJsonFormatters()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var origin = Configuration.GetValue<string>("allowedHosts");
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                    builder =>
                    {
                        builder.WithOrigins($"{origin}");
                    });
            });
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(MyAllowSpecificOrigins);
            app.UseMvc();
        }

我实际上可以看到在调试时从设置文件中正确检索到该值,但是当应用程序启动时,我得到“错误请求 - 无效主机名”。预期的结果是看到任何原点(*)可以被特定值替换。

asp.net-core configuration appsettings
1个回答
0
投票

文档建议应排除端口号(请参阅here),如果没有,请尝试不使用协议:

{
    "app": {
    },
    "connectionStrings": {
        "mainDb": "Server=.\\SQLEXPRESS;Database=MailboxVisualizer;Trusted_Connection=True;"
    },
    "logging": {
        "logLevel": {
            "default": "Debug",
            "system": "Information",
            "microsoft": "Information"
        }
    },
    "allowedHosts": "localhost" // "*", "*.example.com"
}
© www.soinside.com 2019 - 2024. All rights reserved.