C#后台調用跨域MVC服務,帶Cookie驗證


背景

隨着富客戶端框架的盛行,以及眾多優秀的前端js框架,很多情況我們會遇到跨域的問題,而js的ajax請求是不允許直接跨域訪問的,當然你會說可以用JSONP等,但是由於代碼潔癖,不想在前端和后台添加callback,而且很多情況你是無法控制的,需要牽連考慮太多的情況。

所以我直接繞過了,每個前端應用,自帶一個通用后端服務代理,該服務解決跨域問題,自動代理幫前台獲取跨域的數據。 

如何算跨域

雖然是個老問題,但是還是要提醒注意下兩點:同IP,不同端口,數據訪問是跨域的,但是Cookie訪問是可以的(這個讓我很難理解)

解決,源碼
     CookieContainer cookieContainer = new CookieContainer();

     [HttpPost]
        public string CommonPost(string url)
        {
            log.Info(CookieHelper.GetCookie("ITDC_UserName") + "進入方法CommonPost Url=" + url);
            Uri address = new Uri(System.Configuration.ConfigurationManager.AppSettings["RESTfulAPI"].ToString() + url);
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
       //遠程服務,需要加入cookie驗證
            cookieContainer.Add(address, GetCookie("ITDC_UserName"));
            cookieContainer.Add(address, GetCookie("ITDC_UserRole"));
            request.CookieContainer = cookieContainer;
            StringBuilder data = new StringBuilder();
            for (int i = 0; i < Request.QueryString.Count; i++)
            {
                if (Request.QueryString.Keys[i].ToString() == "url") continue;
                data.Append("&" + Request.QueryString.Keys[i].ToString() + "=" + Request.QueryString[i].ToString());
            }
            // Create a byte array of the data we want to send
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString().TrimStart('&'));
            // Set the content length in the request headers
            request.ContentLength = byteData.Length;
            // Write data  
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }  
            string result = "";
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                result = reader.ReadToEnd();
            }
            log.Info(CookieHelper.GetCookie("ITDC_UserName") + " 執行完成 CommonPost Url=" + url);
            return (result);
        }

前台調用

Ext.Ajax.request({url: APIUrl + '/Nebula/CommonPost?url=/Nebula/PostComment/&KlId=1&Msg=ok&Author=admin&Title=文章標題',
                  method: "POST",
                  success: function (response) {
                              Ext.Viewport.unmask();
                              var obj = Ext.decode(response.responseText);
                              Ext.Msg.alert("提示", obj.Msg, Ext.emptyFn);
                           },
                  failure: function (response) {
                              Ext.Viewport.unmask();
                              Ext.Msg.alert("提示", "操作失敗,請檢查網絡!", Ext.emptyFn);
                           }
});

 


免責聲明!

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



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