您当前的位置:首页 > 文章 > C#解决浏览器跨域问题:Response to preflight request doesn‘t pass acces

C#解决浏览器跨域问题:Response to preflight request doesn‘t pass access control check: No ‘Access-Control-Allow-Origin

作者:Zoe97 时间:2023-05-10 阅读数:727 人阅读

1.浏览器为什么不能跨域?
浏览器有一个基本的安全策略--同源策略。为保证用户的信息安全,它对不同源的文档或脚本对当前文档的读写操作做了限制。域名,子域名,端口号或协议不同都属于不同源,当脚本被认为是来自不同源时,浏览器虽然会发出这个请求,但是会拦截响应内容。

2.解决跨域问题
CORS(Cross-Origin Resource Sharing,跨域资源共享),通过向http的请求报文和响应报文里面加入相应的标识告诉浏览器它能访问哪些域名的请求,直接在项目中安装Microsoft.AspNetCore.Cors即可使用。
 
(1).net core
在appsettings中配置可以访问的路径

"cors": {  
    "default": "http://localhost:0000,http://localhost:1111"  
},

在Startup中ConfigureServices下配置

var urls = Configuration.GetSection("cors:default").Value.Split(',');  
services.AddCors(options =>  
{      
    options.AddPolicy("AllowOrigins", builder =>     
   {          
         builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowCredentials();      
   }); 
});

 在Configure中使用

app.UseCors("AllowOrigins"); 
(2)web API

在Web.config中配置:

  <add key="allowOrigins" value="http://localhost:0000,http://localhost:1111"/>
  <add key="allowHeaders" value="*"/> 
  <add key="allowMethods" value="*"/>

在WebApiConfig中配置:          

//跨域配置
    var allowOrigins = ConfigurationManager.AppSettings["cors_allowOrigins"];
    var allowHeaders = ConfigurationManager.AppSettings["cors_allowHeaders"];
    var allowMethods = ConfigurationManager.AppSettings["cors_allowMethods"];
    var globalCors = new EnableCorsAttribute(allowOrigins, allowHeaders, allowMethods);
    config.EnableCors(globalCors);
             
    // Web API 路由
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );



本站大部分文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了您的权益请来信告知我们删除。邮箱:1451803763@qq.com