当前位置: 移动技术网 > IT编程>开发语言>.net > c#解决浏览器跨域问题

c#解决浏览器跨域问题

2019年04月17日  | 移动技术网IT编程  | 我要评论

平鲁房屋出租,百纷网,paulshop

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["alloworigins"];
            var allowheaders = configurationmanager.appsettings["allowheaders"];
            var allowmethods = configurationmanager.appsettings["allowmethods"];
            var globalcors = new enablecorsattribute(alloworigins, allowheaders, allowmethods);
            config.enablecors(globalcors);

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网