背景
隨著富客戶端框架的盛行,以及眾多優(yōu)秀的前端js框架,很多情況我們會(huì)遇到跨域的問題,而js的ajax請(qǐng)求是不允許直接跨域訪問的,當(dāng)然你會(huì)說可以用JSONP等,但是由于代碼潔癖,不想在前端和后臺(tái)添加callback,而且很多情況你是無法控制的,需要牽連考慮太多的情況。
所以我直接繞過了,每個(gè)前端應(yīng)用,自帶一個(gè)通用后端服務(wù)代理,該服務(wù)解決跨域問題,自動(dòng)代理幫前臺(tái)獲取跨域的數(shù)據(jù)。
如何算跨域
雖然是個(gè)老問題,但是還是要提醒注意下兩點(diǎn):同IP,不同端口,數(shù)據(jù)訪問是跨域的,但是Cookie訪問是可以的(這個(gè)讓我很難理解)
解決,源碼
[HttpPost]
public string CommonPost(string url)
{
log.Info(CookieHelper.GetCookie("ITDC_UserName") + "進(jìn)入方法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";
//遠(yuǎn)程服務(wù),需要加入cookie驗(yàn)證
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") + " 執(zhí)行完成 CommonPost Url=" + url);
return (result);
}
|
新聞熱點(diǎn)
疑難解答
圖片精選