8.6 开发自定义HTTP模块
以下的代码片断是为了实现一个支持URL重写的HTTP模块。
多数的Web应用程序使用查询字符串在一个页面和另一个页面之间传输数据。这会给用户记忆和使用URL带来困难。
如:http://localhost/Articles/Ariticles.aspx?AuthorName=Smith
这样的URL不易记忆,且可能导致各种可用性问题。如果允许使用以下URL来访问一页面,那么站点访问者将感到更加轻松:
http://localhost/Articles/Smith.aspx
HTTP模块ArticlesModule
1
using System;
2
using System.Text.RegularExpressions;
3
using System.Web;
4
5
namespace HttpModuleTest
6
{
7
/// <summary>
8
/// This Class finish URL rewriting.
9
/// </summary>
10
public class ArticlesModule : IHttpModule
11
{
12
public ArticlesModule()
13
{
14
//
15
// TODO: Add constructor logic here
16
//
17
}
18
19
public void Init(HttpApplication context)
20
{
21
context.BeginRequest += new EventHandler(context_BeginRequest);
22
}
23
24
public void Dispose()
25
{
26
27
}
28
29
private void context_BeginRequest(object sender, EventArgs e)
30
{
31
HttpApplication app = sender as HttpApplication;
32
HttpContext context = app.Context;
33
34
Regex regex = new Regex(@"Articles/(.*)\.aspx", RegexOptions.IgnoreCase);
35
Match match = regex.Match(context.Request.Path);
36
37
if (match.Success)
38
{
39
string newPath = regex.Replace(context.Request.Path, @"Articles.aspx?AuthorName=$1");
40
context.RewritePath(newPath);
41
}
42
}
43
}
44
}
45
using System;2
using System.Text.RegularExpressions;3
using System.Web;4

5
namespace HttpModuleTest6
{7
/// <summary>8
/// This Class finish URL rewriting.9
/// </summary>10
public class ArticlesModule : IHttpModule11
{12
public ArticlesModule()13
{14
//15
// TODO: Add constructor logic here16
//17
}18

19
public void Init(HttpApplication context)20
{21
context.BeginRequest += new EventHandler(context_BeginRequest);22
}23

24
public void Dispose()25
{26

27
}28

29
private void context_BeginRequest(object sender, EventArgs e)30
{31
HttpApplication app = sender as HttpApplication;32
HttpContext context = app.Context;33

34
Regex regex = new Regex(@"Articles/(.*)\.aspx", RegexOptions.IgnoreCase);35
Match match = regex.Match(context.Request.Path);36

37
if (match.Success)38
{39
string newPath = regex.Replace(context.Request.Path, @"Articles.aspx?AuthorName=$1");40
context.RewritePath(newPath);41
}42
}43
}44
}45


