.netcore 跨域问题

2023-03-12

CORS(跨域资源共享)是一种W3C标准,允许服务器放宽同源策略。使用CORS,服务器可以在显式允许某些跨域请求时拒绝其他跨域请求。CORS是相比其他跨域技术(比如JSONP)更安全、更灵活。

ASP.NET Core跨域问题需要再 StartUp.cs 文件中进行相关配置。

ConfigureServices:

            services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
.AllowCredentials();
}));

由于ASP.NET CORE 2.1, 其Cors组件已经升级,出于安全考虑必须明确要允许的内容。 如果要允许凭据,则Access-Control-Allow-Origin不能使用*。 您必须指定确切的协议+域+端口。

            services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.WithOrigins(new string[] { "http://127.0.0.1:5000" })
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));

不想做任何限制就将AllowAnyOrigin替换为SetIsOriginAllowed(_ => true)就可以解决。

            services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod()
.SetIsOriginAllowed(_ => true)
.AllowAnyHeader()
.AllowCredentials();
}));

  

在Configure中,添加配置

注意: app.UseCors("CorsPolicy"); 要写在app.UseAuthorization(); 后面,否则会报错。

            app.UseAuthorization();
app.UseAuthentication();
//配置Cors
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("any");
});

  

.netcore 跨域问题的相关教程结束。

《.netcore 跨域问题.doc》

下载本文的Word格式文档,以方便收藏与打印。