您的位置:首页 > 理论基础 > 计算机网络

IHttpModule实现URL重写

2012-06-29 13:25 253 查看

1、用自定义IHttpModule实现URL重写

一般来说,要显示一些动态数据总是采用带参数的方式,比如制作一个UserInfo.aspx的动态页面用于显示系统的UserInfo这个用户信息表的数据,那么需要在其后带上一个参数来指定要显示的用户信息,比如UserInfo.aspx?UserId=1用于显示表中编号为1的用户的信息,如果为2则显示表中编号为2的用户信息。在一些系统中我们可能看到的不是这样的效果,可能会看到形如UserInfo2.aspx这样的形式(当然形式可以多样,只要有规律就行),当点击这样一个链接时看到的效果和UserInfo.aspx?UserId=2的效果一样,这里就用到了URL地址重写的目的。

在实例化HttpApplication类时会根据web.config中的配置(包括系统级和当前网站或虚拟目录级)实例化所有实现IHttpModule接口的集合,然后会将HttpApplication类的实例作为参数依次调用每个实现了IHttpModule接口的类的实例的Init()方法,在Init方法中可以添加对请求的特殊处理。在HttpApplication中有很多事件,其中第一个事件就是BeginRequest事件,在这个事件中我们可以对用户请求的URL进行判断,如果满足某种要求,可以按另外一种方式来进行处理。

比如,当接收到的用户请求的URL是UserInfo(\\d+).aspx这种形式时(这里采用了正则表达式,表示的是UserInfo(数字).asp这种URL)我们将会运行UserInfo.aspx?UserId=(\\d+)这样一个URL,这样网页就能正常显示了。

当然实现URL地址重写还需要借助一个类:HttpContext。HttpContext类中定义了RewritePath 方法,这个方法有四种重载形式,分别是:
RewritePath(String) 使用给定路径重写 URL。
RewritePath(String, Boolean) 使用给定路径和一个布尔值重写 URL,该布尔值用于指定是否修改服务器资源的虚拟路径。
RewritePath(String, String, String) 使用给定路径、路径信息和一个布尔值重写 URL,该布尔值用于指定是否修改服务器资源的虚拟路径。
RewritePath(String, String, String, Boolean) 使用给定虚拟路径、路径信息、查询字符串信息和一个布尔值重写 URL,该布尔值用于指定是否将客户端文件路径设置为重写路径。

对于这里四个重载方法的区别我不一一详细描述,因为在这里只用带一个参数的重载方法就能满足本文提出的要求。
我们的步骤如下:
首先编写自定义IHttpModule实现,这个定义只定义了两个方法Dispose()和Init()。在这里我们可以不用关注Dispose()这个方法,这个方法是用来实现如何最终完成资源的释放的。在Init方法中有一个HttpApplication参数,可以在方法中可以自定义对HttpApplication的事件处理方法。比如这里我们的代码如下:

public void Init(HttpApplication context)

{

context.BeginRequest += new EventHandler(BeginRequest);

}


public void BeginRequest(object sender, EventArgs e)

{

HttpApplication application = sender as HttpApplication;

HttpContext context = application.Context;

HttpResponse response = context.Response;


//重写后的URL地址

string path = context.Request.Path;

string file = System.IO.Path.GetFileName(path);

Regex regex = new Regex("UserInfo(\\d+).aspx", RegexOptions.Compiled);

Match match = regex.Match(file);


if (match.Success)

    {

string userId = match.Groups[1].Value;

//将其按照UserInfo.aspx?UserId=123这样的形式重写,确保能正常执行

string rewritePath = "UserInfo.aspx?UserId=" + userId;

context.RewritePath(rewritePath);

    }

}


注意在上面的代码中采用了正则表达式来进行匹配,使用正则表达式的好处就是在处理格式化文本时相当灵活。除此之外,我们在处理方法中仅仅对满足要求的URL进行重写,对于不满足要求的URL则无需进行重写,所以这样就不会干扰没有重写的URL的正常运行(比如Index.aspx)。

从那段从《ASP.NET夜话》摘出的话中可以看出,仅仅是编写自己的IHttpModule实现还是不够的,我们还需要让处理Web请求的程序直到我们编写的IHttpModule实现的存在,这就需要在web.config中配置。在本实例中只需要在本ASP.NET项目中的web.config节点中增加一个<httpModules></httpModules>节点(如果已存在此节点则可以不用添加),然后在此节点中增加一个配置即可,对于本实例,这个节点最终内容如下:

<httpModules>

<add name="MyHttpModule" type="WebApplication1.MyHttpModule,WebApplication1"/>

</httpModules>


UserInfo.aspx.cs

if (!Page.IsPostBack)

    {

string queryString = Request.QueryString["UserId"];

int userId = 0;

if (int.TryParse(queryString, out userId))

        {

Response.Write(userId.ToString());

}

else

        {

Response.Write("error");

}

    }


效果图






以上内容转自:http://blog.csdn.net/zhoufoxcn/archive/2009/07/14/4346356.aspx

2、使用URLRewriter

web.config的配置

<?xml version="1.0"?>

<configuration>

<configSections>

<section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />

</configSections>

<RewriterConfig>

<Rules>

<RewriterRule>

<LookFor>~/news/(.[0-9]*)\.html</LookFor>

<SendTo>~/news/new.aspx?id=$1</SendTo>

</RewriterRule>

<RewriterRule>

<LookFor>~/web/index.html</LookFor>

<SendTo>~/web/index.aspx</SendTo>

</RewriterRule>

</Rules>

</RewriterConfig>

<system.web>

<httpHandlers>

<add verb="*" path="*.aspx" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />

<add verb="*" path="*.html" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />

</httpHandlers>

<compilation debug="true"/>

</system.web>

</configuration>


这里简单介绍一下:

<RewriterConfig>

<Rules>

<RewriterRule>

<LookFor>要查找的模式</LookFor>

<SendTo>要用来替换模式的字符串</SendTo>

</RewriterRule>

<RewriterRule>

<LookFor>要查找的模式</LookFor>

<SendTo>要用来替换模式的字符串</SendTo>

</RewriterRule>

</Rules>

</RewriterConfig>


httpHandlers的设置主要是配合IIS将请求重新定义处理,这里也比较关键,如果不存在合理的httpHandlers,那么,访问肯定会失败的。关于正则表达式,可以到百度里搜索:"常用正则表达式",会有很多。

News.aspx.cs

if (!Page.IsPostBack)

    {

// http://localhost:10445/News/1.html

string queryString = Request.QueryString["Id"];

int newsId = 0;

if (int.TryParse(queryString, out newsId))

        {

Response.Write(newsId.ToString());

}

else

        {

Response.Write("error");

}

    }


配置IIS解析.html文件
右键点我的电脑-->管理-->展开'服务和应用程序'-->internet信息服务-->找到你共享的目录-->右键点击属性 -->点击'配置'-->映射下面 -->找到.aspx的可执行文件路径 复制路径-->粘贴路径-->扩展名为".html"-->然后把检查文件是否存在的勾去掉这样就可以了,如果遇到“确定”按钮失效,可以用键盘事件编辑路径即可解决。

效果图






以上内容转自:/article/5956657.html

注意

HttpModule默认处理aspx页面没有问题,但是如果在IIS上配置html也通过HttpModule处理时会出现死循环无法跳出html页面的问题,在web.config上加上

<add verb="*" path= "*.htm" type= "System.Web.StaticFileHandler"/></httpHandlers>

可解决。

3、修改UrlRewriter 实现泛二级域名

大家应该知道,微软的URLRewrite能够对URL进行重写,但是也只能对域名之后的部分进行重写,而不能对域名进行重写,如:可将 http://http://www.abc.com//1234/ 重写为 http://www.abc.com/show.aspx?id=1234 但不能将
http://1234.abc.com/ 重写为 http://www.abc.com/show.aspx?id=1234。

要实现这个功能,前提条件就是 http://www.abc.com/ 是泛解析的,再就是要修改一下URLRewriter了。
总共要修改2个文件

1.BaseModuleRewriter.cs

protected virtual void BaseModuleRewriter_AuthorizeRequest(object sender, EventArgs e)

{

HttpApplication app = (HttpApplication)sender;

//	Rewrite(app.Request.Path, app);

Rewrite(app.Request.Url.AbsoluteUri, app);

}

就是将 app.Request.Path 替换成了 app.Request.Url.AbsoluteUri

// iterate through each rule...

for(int i = 0; i < rules.Count; i++)

{

// get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)

//	string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";

string lookFor = "^" + rules[i].LookFor + "$";


// Create a regex (note that IgnoreCase is set...)

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


// See if a match is found

if (re.IsMatch(requestedPath))

	{

// match found - do any replacement needed

string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo));


// log rewriting information to the Trace object

app.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);


// Rewrite the URL

RewriterUtils.RewriteUrl(app.Context, sendToUrl);

break;		// exit the for loop

}

}


string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";
改成了
string lookFor = "^" + rules[i].LookFor + "$";

web.config

<RewriterRule>

<LookFor>http://(\w+)\.lost\.com/</LookFor>

<SendTo>/abc.aspx?name=$1</SendTo>

</RewriterRule>


abc.aspx.cs

if (!Page.IsPostBack)

    {

Response.Write(Request.QueryString["name"]);

    }


效果图







1.域名解析问题
输入了域名http://1234.abc.com/,浏览器提示找不到网页。首先,你应该确认你的域名是否支持泛域名解析,就是让所有的二级,三级域名都指向你的server。其次,要保证你的站点是服务器上的默认站点,就是80端口主机头为空的站点即可以直接用IP可以访问的http://1234.abc.com/,要么要提示你的站点的错误信息,要么会正确的执行你定义的URLRewrite,要么显示你的站点的首页。

2.不能执行重写的问题
如果你确认你的域名解析是正确的,但是还是不能重写,访问http://1234.abc.com/会提示路径"/"找不到...,
如果是这样的话,你先添加 ASPNET_ISAPI的通配符应用程序映射(这一步是必需的,Sorry!没有在上篇文章中提出来)。
操作方法:IIS站点属性 ->主目录 -> 配置





3. 默认首页失效,因为把请球直接交给asp.net处理,IIS定义的默认首页将会失效,出现这种情形:
访问http://www.abc.com/ 不能访问首页,而通过http://1234.abc.com/default.aspx可以访问。
为解决这个问题,请自己在Web.Config中设置 lookfor / to /default.aspx 或 index.aspx ..的重写,完全可以解决问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: