.net Core 3.1 webAPI跨域问题解决方案
在Startup.ConfigureServices中,添加服务
注意:.net Core 3.1版本 Cors配置不能同时启用 AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()
否则报错 System.InvalidOperationException
HResult=0x80131509
Message=The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the CORS policy by listing individual origins if credentials needs to be supported.
Source=Microsoft.AspNetCore.Cors
解决方法:
Configure中添加:
//启动跨域
app.UseCors(“any”);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors(“any”);
});
ConfigureServices中添加:
//添加跨域支持
services.AddCors(options =>
{
options.AddPolicy(“any”, builder =>
{
builder.WithMethods(“GET”, “POST”, “HEAD”, “PUT”, “DELETE”, “OPTIONS”)
//.AllowCredentials()//指定处理cookie
.AllowAnyOrigin(); //允许任何来源的主机访问
});
});