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/
博客版權: 本文以學習、研究和分享為主,歡迎轉載,但必須在文章頁面明顯位置給出原文連接。
如果文中有不妥或者錯誤的地方還望高手的你指出,以免誤人子弟。如果覺得本文對你有所幫助不如【推薦】一下!如果你有更好的建議,不如留言一起討論,共同進步!
再次感謝您耐心的讀完本篇文章。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM