[英]CORS not working in ASP.NET core Web API project
I built an ASP.NET core Web API (net core 3.1), and I try to enable CORS but it seems not working.我构建了一个 ASP.NET 核心 Web API (网核心 3.1),我尝试启用 Z5A8ZFEFF0B4BDE3B7D929 它似乎不起作用。
Startup.cs:启动.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();
}
Controller: Controller:
[Route("api/[controller]")]
[ApiController]
public class airdata_updateController : ControllerBase
{
[EnableCors("AllowMyOrigin")]
[HttpGet]
public string test()
{
return "ok";
}
...
}
I use Postman test my API on local computer and it working well: local computer我在本地计算机上使用 Postman 测试我的 API,它运行良好:本地计算机
But I use Postman on other computer in the same LAN to call my API, it failed: other computer但是我在同一局域网中的其他计算机上使用 Postman 来调用我的 API,它失败了:其他计算机
What should I do?我应该怎么办?
Try this:尝试这个:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCors(
options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()
);
...
}
You won't need any decorators in your controller methods, the specified CORS policy ( AllowAnyOrigin, AllowAnyHeader, AllowAnyMethod) is applied in all of them.您的 controller 方法中不需要任何装饰器,所有这些方法都应用了指定的 CORS 策略(AllowAnyOrigin、AllowAnyHeader、AllowAnyMethod)。 In order to customize the policy, check https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
要自定义策略,请查看https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
maybe this option can help you.也许这个选项可以帮助你。
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder => builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.