本文是
用IHttpModule解决输入中文地址乱码问题(一) 的续文。
上文说到,需要对已有的地址进行GB2312编码,这样大大增加了工作量,有没更好的办法呢?
1
public
class
HookModule : IHttpModule
2
{
3
4
#region
IHttpModule 成员
5
6
public
void
Dispose()
7
{
8
9
}
10
11
public
void
Init(HttpApplication context)
12
{
13
context.BeginRequest
+=
new
EventHandler(context_BeginRequest);
14
}
15
16
void
context_BeginRequest(
object
sender, EventArgs e)
17
{
18
19
HttpApplication application
=
(HttpApplication)sender;
20
HttpContext context
=
application.Context;
21
IdentifyEncoding ie
=
new
IdentifyEncoding();
22
23
24
string
rawurl
=
context.Request.RawUrl;
25
rawurl
=
HttpUtility.UrlDecode(rawurl);
26
byte
[] bytes
=
System.Web.HttpUtility.UrlDecodeToBytes(rawurl, Encoding.Default);
27
28
Encoding enc
=
Encoding.Default;
29
try
30
{
31
enc
=
Encoding.GetEncoding(ie.GetEncodingName(IdentifyEncoding.ToSByteArray(bytes)));
32
}
33
catch
{ }
34
string
s
=
enc.GetString(bytes);
35
context.RewritePath(s);
36
}
37
38
39
40
#endregion
41
}
这里用了一个检查当前请求地址六编码的函数。这个函数实际上是从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://files.cnblogs.com/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源码。
全文完。
http://www.cnblogs.com/ by yurow.