.Net Core 处理跨域问题Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

2023-02-15,,,,

网页请求报错:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

如图:

跨域问题解决原理

CORS全称Cross-Origin Resource Sharing,中文全称跨域资源共享。它解决跨域问题的原理是通过向http的请求报文和响应报文里面加入相应的标识告诉浏览器它能访问哪些域名的请求。

比如我们向响应报文里面增加这个Access-Control-Allow-Origin:http://localhost:8081,就表示支持http://localhost:8081里面的所有请求访问系统资源。

其他更多的可以去网上找找。

在.net Core解决方案

WebApi项目中的

Startup.cs类方法体 ConfigureServices 内加上

  services.AddCors(options =>
{
options.AddPolicy(anyAllowSpecificOrigins, corsbuilder =>
{
var corsPath = Configuration.GetSection("CorsPaths").GetChildren().Select(p => p.Value).ToArray();
corsbuilder.WithOrigins(corsPath)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();//指定处理cookie
                });
});

appsettings.json加上以下配置

  "CorsPaths": { //配置跨域的地址【跨域地址加到这里就可以访问 "参数名":"跨域地址"】
"OriginAll": "*",
"OriginOnA": "http://localhost:8080",
"OriginOneC": "http://localhost:8081",
"OriginOneD": "http://localhost:8082",
"OriginOneE": "http://localhost:8083"
}

.Net Core 处理跨域问题Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource的相关教程结束。

《.Net Core 处理跨域问题Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.doc》

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