ASP.NET URL重写浅析

本文介绍了一种在ASP.NET应用程序中实现URL重写的简单方法。通过在Global.asax.cs文件中的Application_BeginRequest事件处理程序内使用正则表达式匹配和替换请求路径,可以灵活地更改客户端看到的URL,而不会改变实际的页面地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详细参见: http://www.microsoft.com/china/msdn/library/webservices/asp.net/URLRewriting.mspx

最简单的实现,就是在 Global.asax.cs中 Application_BeginRequest 或者是 Application_AuthenticateRequest 事件处理中,对请求的URL进行判断并进行重写:

protected void Application_BeginRequest(Object sender, EventArgs e)

{

HttpApplication app = (HttpApplication) sender;

string requestedPath = app.Request.Path;

string lookFor = @"^/webapptest/urlrewritetest/department/(/w+)/.aspx$";

string sendTo = "/webapptest/urlrewritetest/webform2.aspx?dept=$1";

Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

if (re.IsMatch(requestedPath))

{

string sendToUrl = re.Replace(requestedPath, sendTo);

app.Context.RewritePath(sendToUrl);

}

}

重写主要利用了 HttpContext.RewritePath 方法。

执行效果是将:

http://localhost/WebAppTest/URLRewriteTest/department/Finance.aspx

重写为:

http://localhost/WebAppTest/URLRewriteTest/WebForm2.aspx?Dept=Marketing

<!--EndFragment-->

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值