用IHttpModule解决输入中文地址乱码问题(二)

上文说到,需要对已有的地址进行GB2312编码,这样大大增加了工作量,有没更好的办法呢?

 
     public class HookModule : IHttpModule
     {
 
         #region IHttpModule 成员
 
 
         public void Dispose()
         {
            
         }
 
 
         public void Init(HttpApplication context)
         {
             context.BeginRequest += new EventHandler(context_BeginRequest);
         }
 
 
         void context_BeginRequest(object sender, EventArgs e)
         {
            
             HttpApplication application = (HttpApplication)sender;
             HttpContext context = application.Context;
             IdentifyEncoding ie = new IdentifyEncoding();
 
            
 
             string rawurl = context.Request.RawUrl;
             rawurl = HttpUtility.UrlDecode(rawurl);
 
             byte[] bytes = System.Web.HttpUtility.UrlDecodeToBytes(rawurl, Encoding.Default);

             Encoding enc = Encoding.Default;
             try
             {
                 enc = Encoding.GetEncoding(ie.GetEncodingName(IdentifyEncoding.ToSByteArray(bytes)));
             }
 
             catch { }
 
             string s = enc.GetString(bytes);
             context.RewritePath(s);
         }
 
 
 
 
          #endregion
    }



这里用了一个检查当前请求地址六编码的函数。这个函数实际上是从java转过来的(Create By lion),用来做蜘蛛自动侦测网站编码还不错。
由于代码较长,需要的可以从附件下载。

在这种处理中,实际上还有另外一个问题,假如,你把链接的中文编码成utf-8是会出现问题的。

一下是详细的用法:

1、 网页中有 <a href="http://localhost/a.aspx?key=就是中文">http://localhost/a.aspx?key=就 是中文</a> 这样的中文链接,无论这个网页的编码是什么类型的,都是不会出现乱码的;
2、网页中有<a href="http://localhost/a.aspx?key=System.Web.HttpUtility.UrlEncode("就是中文",Encoding.GetEncoding("gb2312"))
">http://localhost/a.aspx?key=就是中文</a>这样的中文链接,无论这个网页的编码是什么类型的,都是不会出现乱码的;
3、比如,使用地址重写中,有这个样的链接 "http://localhost/w/就是中文" ,无论你在IE中还是FF中直接地址栏输入都不会出现乱码。

附件:
1、DLL(http://www.cnblogs.com/Files/birdshover/YesHJ.Search.GBHookModule.rar)

注:附件中的DLL可以在WEB.CONFIG中使用
      <httpModules>
        <add name="GB" type="YesHJ.Search.GBHookModule.HookModule,YesHJ.Search.GBHookModule"/>
    <add name="Rewriter" type="XP.Framework.HttpModule.UrlRewriter.HttpModule,XP.Framework.HttpModule.UrlRewriter"/>
      </httpModules>

在根目录建立文件Rewriter.config,放入重写规则,例如

<?xml version="1.0" encoding="utf-8" ?>
<Rules>
<RewriterRule>
  <LookFor>/w/(?<type>[a-z])/(?<word>[^/]*)/(?<page>\d+)/*</LookFor>
  <SendTo>~/so.aspx?t=$type$&key=$word$&p=$page$</SendTo>
</RewriterRule>
<RewriterRule>
  <LookFor>/w/(?<type>[a-z])/(?<word>[^/]*)/?</LookFor>
  <SendTo>~/so.aspx?t=$type$&key=$word$</SendTo>
</RewriterRule>
<RewriterRule>
  <LookFor>/w/(?<word>[^/]*)/(?<page>\d+)/?</LookFor>
  <SendTo>~/so.aspx?key=$word$&p=$page$</SendTo>
</RewriterRule>
<RewriterRule>
  <LookFor>/w/(?<word>[^/]*)/?</LookFor>
  <SendTo>~/so.aspx?key=$word$</SendTo>
</RewriterRule>
</Rules>

可以用源代码查看工具,查看DLL源码。

全文完。

共有0个回答