【发布时间】:2020-11-01 12:47:58
【问题描述】:
我构建了一个 ASP.NET core Web API(net core 3.1),我尝试启用 CORS,但它似乎不起作用。
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder =>
{
builder.SetIsOriginAllowed(t => true)
.AllowCredentials();
});
});
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowMyOrigin");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseHttpsRedirection();
}
控制器:
[Route("api/[controller]")]
[ApiController]
public class airdata_updateController : ControllerBase
{
[EnableCors("AllowMyOrigin")]
[HttpGet]
public string test()
{
return "ok";
}
...
}
我使用 Postman 在本地计算机上测试我的 API,它运行良好: local computer
但是我在同一局域网中的其他计算机上使用 Postman 来调用我的 API,它失败了: other computer
我该怎么办?
【问题讨论】:
-
这根本不是 CORS 问题。错误消息就在那里说明您遇到了连接超时问题。检查您的防火墙设置以及您的开发网络服务器是否配置为允许远程连接。
-
你不仅需要在本地主机监听,还需要在本地网络接口监听。
-
谢谢你,戴!你是对的,这是防火墙问题。
标签: c# asp.net-core asp.net-core-webapi