HttpContext rewritePath后中文乱码

文章为转载

由于种种原因,最近将服务器上部署的网站修改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('&'));
}

  

问题是解决了,不过这肯定是很笨的一种方法。先临时把问题解决,再寻找更好的办法了。希望遇到类似问题的提供意见,同时也希望遇到类似问题的人能够快速定位问题

原文地址:https://www.cnblogs.com/xuyufeng/p/4682453.html