导读:B5教程网今天分享一个C#后台如何调用跨域MVC服务并实现Cookie验证??是不是大家都遇到过这样的问题呢?背景随着富客户端框架的盛行,以及...
B5教程网今天分享一个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);
- }
- });