当我在我的appsettings.Development.json文件中使用“ allowedHosts”:“ http://localhost:9000”,然后尝试在Startup.cs中检索值时,API会引发“错误请求-无效的主机名”异常>
使用“ 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();
}
我实际上可以看到调试时从设置文件中正确检索了该值,但是当应用程序启动时,我收到“错误请求-无效的主机名”。预期结果是看到任何原点(*)都可以替换为特定值。
答案 0 :(得分:0)
文档建议应排除端口号(请参阅here),尝试不使用端口号且不使用协议:
{
"app": {
},
"connectionStrings": {
"mainDb": "Server=.\\SQLEXPRESS;Database=MailboxVisualizer;Trusted_Connection=True;"
},
"logging": {
"logLevel": {
"default": "Debug",
"system": "Information",
"microsoft": "Information"
}
},
"allowedHosts": "localhost" // "*", "*.example.com"
}