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

來源:互聯網
上載者:User
背景

隨著富用戶端架構的盛行,以及眾多優秀的前端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);                           }});

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.