由於種種原因,最近將服務器上部署的網站修改4.0框架。但悲劇的問題出現了,發現搜索中文的時候關鍵詞都成亂碼了。
在網上查找相關資料得到幾種相關解決方案如下:
- 服務器打補丁server2008 打sp2補丁中文語言包
- url中中文先通過Server.UrlEncode編碼
- 修改網站編碼
根據以上提示進行一步一步解決 檢查服務器系統已經是sp2的中文系統,網站搜索是通過js跳轉的無法進行Server.UrlEncode編碼,修改網站編碼比較麻煩而且有可能導致其他問題,所以以上方法都行不通。
只能自己想辦法了,自己添加一個簡單測試頁面 http://www.test.cn/test.aspx?kw=測試 頁面輸出QueryString時候發現輸出的中文是正常的。再對搜索頁面的地址不進行url重寫的情況下訪問測試,發現同樣中文同樣是正常的。於是初步確定是在URLRewriter中轉發時候參數傳遞過程中出現問題。按照之前查到的使用Server.UrlEncode對參數進行編碼。經過一番調試后終於是沒有亂碼了。
修改代碼RewriterUtils.cs 的RewriteUrl方法
internal static void RewriteUrl(HttpContext context, string sendToUrl, out string sendToUrlLessQString, out string filePath)
{
if (context.Request.QueryString.Count > 0)
{
if (sendToUrl.Contains("?"))
{
sendToUrl = sendToUrl + "&" + context.Request.QueryString;
}
else
{
sendToUrl = sendToUrl + "?" + context.Request.QueryString;
}
}
string queryString = string.Empty;
sendToUrlLessQString = sendToUrl;
int tempIndex = sendToUrl.IndexOf('?');
if (tempIndex != -1)
{
sendToUrlLessQString = sendToUrl.Substring(0, tempIndex);
queryString = sendToUrl.Substring(tempIndex + 1);
}
filePath = context.Server.MapPath(sendToUrlLessQString);
//iis7 獲取亂碼問題
var list = queryString.Split('&');
var newQueryStr = string.Empty;
for (int i = 0; i < list.Length; i++)
{
var arr = list[i].Split('=');
if (arr.Length > 1)
{
newQueryStr = newQueryStr + arr[0] + "=" + context.Server.UrlEncode(arr[1]) + "&";
}
else
{
newQueryStr = newQueryStr + "&";
}
}
context.RewritePath(sendToUrlLessQString, string.Empty, newQueryStr.TrimEnd('&'));
}
問題是解決了,不過這肯定是很笨的一種方法。先臨時把問題解決,再尋找更好的辦法了。希望遇到類似問題的提供意見,同時也希望遇到類似問題的人能夠快速定位問題
