今天在用HttpWebRequest類向一個遠程頁面post數據時,遇到了一個怪問題,總是出現500的內部服務器錯誤,通過查看遠程服務器的log,發現報的是“無效的視圖狀態”錯誤:
通過對比自己post的__VIEWSTATE和服務器接收到的__VIEWSTATE的值(通過服務器的HttpApplication的BeginRequest事件可以取到Request里的值),發現__VIEWSTATE中的一個+號被替換成了空格。(由於ViewState太長,這個差異也是仔細觀察了很久才看出來的)
造成這個錯誤的原因在於+號在url中是特殊字符,遠程服務器在接受request的時候,把+轉成了空格。同樣的,如果想post的數據中有&、%等等,也會被服務器轉義,所以我們在post的數據的時候,需要先把數據UrlEncode一下。url encode在bs開發中本來是一個很常見的問題,但沒想到還是在這里栽了跟頭。
修改后的post數據的示例代碼如下,注意下面加粗的那句話:
public HttpWebResponse GetResponse(string url)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = CookieContainer;
if (Parameters.Count > 0)
{
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//data要UrlEncode
var postData = string.Join("&", Parameters.Select(
p =>
string.Format("{0}={1}", p.Key,
System.Web.HttpUtility.UrlEncode(p.Value, Encoding))).ToArray());
var data = Encoding.GetBytes(postData);
req.ContentLength = data.Length;
using (var sw = req.GetRequestStream())
{
sw.Write(data, 0, data.Length);
}
}
req.Timeout = 40 * 1000;
var response = (HttpWebResponse)req.GetResponse();
return response;
}