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

网页请求报错:

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

跨域问题解决原理

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

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

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

在.net Core解决方案

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

  • Startup.cs类方法体 ConfigureServices 内加上

    .Net Core 处理跨域问题Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
  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加上以下配置

    .Net Core 处理跨域问题Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
  "CorsPaths": { //配置跨域的地址【跨域地址加到这里就可以访问 "参数名":"跨域地址"】
"OriginAll": "*",
"OriginOnA": "http://localhost:8080",
"OriginOneC": "http://localhost:8081",
"OriginOneD": "http://localhost:8082",
"OriginOneE": "http://localhost:8083"
}
上一篇:[转载]SpringMVC解决跨域问题


下一篇:B树及2-3树的python实现