用IHttpModule做自己的URL重写

本文介绍了一种自定义URL重写模块的方法,通过在.NET应用程序中实现IHttpModule接口,实现了特定格式URL的自动重定向,并保持了地址栏中的原始URL不变。

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

用网上下载的UrlRewriteModule URL重写组件发现有时在打开页面的时候会出错(错误一时没有记下来·!!),但是再刷新页面的时候又好了,于是想自己写一个URL重写的,以得以前看视频的时候说是要URL重写的话可在Module中写,上网查了一下相关的资料,写了一个简单的Module来进行URL重写,记录如下,以备后用:
web.config的配置:

<httpModules>
<!-- 测试 -->
<add name="ModuleTest" type="ModouleTest"/>
<!-- 测试结束 -->
</httpModules>


ModouleTest.cs

/*
* 作者: 牛腩
* 创建时间: 2009-9-2 9:59:30
* Email: 164423073@qq.com
* 说明: URL重写Module
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

/// <summary>
///URL重写Module
/// </summary>
public class ModouleTest : IHttpModule
{
public ModouleTest()
{

}

#region IHttpModule 成员

void IHttpModule.Dispose()
{
throw new NotImplementedException();
}

void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Application_BeginRequest);
}

#endregion

private void Application_BeginRequest(object sender, EventArgs e)
{

HttpApplication application = (HttpApplication)sender;

HttpRequest request = application.Request;

HttpResponse response = application.Response;

HttpServerUtility server = application.Server;

string url = request.Url.ToString();

/*
* 只要输入的地址中有niunantest/的都会跳转并把/后头的字符传过去,如:
* http://localhost:3212/ModuleTest/niunantest/43242
* http://localhost:3212/ModuleTest/niunantest/abd3345
* http://localhost:3212/ModuleTest/niunantest/牛腩
*/
Regex reg = new Regex(@"niunantest/(\w+)");

if (reg.IsMatch(url))
{
Match m = reg.Match(url);
string value = m.Groups[1].Value;
//response.Write("匹配的值:" + value + "<br>");
server.Transfer("~/default.aspx?str=" + value); // 使用response.Redirect会让地址栏中的地址改变
}
}
}


个人理解,其实module就相当于jsp中的过滤器(如果有的话),每个页面在呈现之前必须得先经过module,那么我们就可以在module中判断当前的URL地址,如果符合某个格式的就可以跳转到对应的页面,在这里用到了server.Transfer跳转是为了不让地址栏中的地址改变。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值