本文是用IHttpModule解决输入中文地址乱码问题(一) 的续文。
上文说到,需要对已有的地址进行GB2312编码,这样大大增加了工作量,有没更好的办法呢?
\n
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 }\n
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 }\n