Asp.Net 跨域,Asp.Net MVC 跨域,Session共享,CORS,Asp.Net CORS,Asp.Net MVC CORS,MVC CORS

比如 http://www.test.com 和 http://m.test.com

一、简单粗暴的方法 Web.Config  

<system.web>
        <!--其他配置 省略……-->
        <httpCookies  domain="test.com" /><!--同一顶级域名-->
  </system.web>


 <handlers>
      <!--其他配置 省略……-->
      <!--<remove name="OPTIONSVerbHandler" />--><!--这里一定得要注释掉OPTIONSVerbHandler。意思允许支持 OPTIONS -->
 </handlers>

    <httpProtocol>
     <!--其他配置 省略……-->
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://www.test.com" /><!--   允许指定的地址-->
        <add name="Access-Control-Allow-Credentials" value="true" /><!--允许携带Cookie-->
        <add name="Access-Control-Allow-Methods" value="GET, HEAD, OPTIONS, POST, PUT" />
        <add name="Access-Control-Allow-Headers" value="cache-control,content-type,if-modified-since,origin,x-requested-with,content-language" /><!--header支持的都填入,不够的继续添加-->
      </customHeaders>
    </httpProtocol>

二、支持自定义

 web.config

<system.web>
        <!--其他配置 省略……-->
        <httpCookies  domain="test.com" /><!--同一顶级域名-->
  </system.web>

<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

Global.asax

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var app = ((System.Web.HttpApplication)sender);
            if (!string.IsNullOrWhiteSpace(app.Request.Headers["Origin"]))
            {
                app.Response.AppendHeader("Access-Control-Allow-Credentials", "true");
                app.Response.AppendHeader("Access-Control-Allow-Origin", app.Request.Headers["Origin"]);//替换自定义即可,如:“http://www.test.com”

                if (!string.IsNullOrWhiteSpace(app.Request.Headers["Access-Control-Request-Method"]))
                {
                    app.Response.AppendHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT");
                    app.Response.AppendHeader("Access-Control-Allow-Headers", "cache-control,content-type,if-modified-since,origin,x-requested-with,content-language");
                    app.Response.End();                    
                }
            }
        }

 

 

 客户端 AJAX 支持跨域携带Cookie

//原生请求方式:
var xhr = new XMLHttpRequest();  
xhr.withCredentials = true; 


//JQuery 请求方式
$.ajaxSetup({crossDomain: true, xhrFields: {withCredentials: true}});

 

博客地址: https://www.cnblogs.com/smartstar/
博客版权: 本文以学习、研究和分享为主,欢迎转载,但必须在文章页面明显位置给出原文连接。
如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步!
再次感谢您耐心的读完本篇文章。
posted @ 2018-10-11 14:47  慧☆星  阅读(2342)  评论(4编辑  收藏  举报