因为最近有项目用到.net Core 3.1 webAPI,接口有跨域问题,网上百度了一些都是用配置Cors来解决的
现在我记录一下,在解决问题过程中出现的问题
在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
//添加cors 服务 配置跨域处理
services.AddCors(options =>
{
options.AddPolicy("any", builder =>
{
builder.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
//.AllowCredentials()//指定处理cookie
.AllowAnyOrigin(); //允许任何来源的主机访问
});
});
在Startup.Configure中,添加配置
注意: app.UseCors("any"); 要写在app.UseAuthorization(); 后面,否则会报错。
Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).VM310:3 GET http://链接 net::ERR_CONNECTION_REFUSED
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
//配置Cors
app.UseCors("any");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("any");
});
这些配置完成就能解决跨域问题了,欢迎大家指出错误或评论区讨论问题