代码改变世界

IHttphandler之Url重写

2009-06-29 09:39  三把刷子  阅读(737)  评论(0编辑  收藏  举报

IHttphandler是什么,表面上看他是一个接口,实际上他可以把客户端提交的请求进行处理后返回给客户端。

IHttphandler接口包括IsReusable属性和ProcessRequest方法,IsReusable属性是指是否可以重用,ProcessRequest方法用来处理客户端的请求。

群里有人提出了Url重写的需求,闲来无事便帮忙实现了下。那位兄弟的需求如下:


输入如下格式
http://localhost:2868/cgi/redirectform?uid=pxl&pwd=12346
即可看到URL重写实际显示的页面为
handler下的RedirectForm.aspx


首先来看下web.config里的配置信息:

<httpHandlers>
      <add verb="*" path="cgi/*" type="MyHttpHandler.UrlChangeHandler,MyHttpHandler"/>    </httpHandlers>


1)verb代表客户端请求类型,“*”代表任何请求类型,当然也可以是“GET,HEAD”,“POST,GET”等。


2)path代表客户端请求路径,这个很有用途滴,服务器控件的响应可以利用(后续的验证码服务器控件文章中有详细描述,敬请观看),path设置为“cgi/*”其意义是如果客户端发出的路径请求,其中“*”代表任意字符串,比如:cgi/test,cgi/123456,cgi/redirectform?uid=pxl&pwd=123456等。

3)type顾名思义就是类了,格式为“[命名空间].[处理类名称],[命名空间]”,其中的处理类名称即为实现了IHttphandler接口的类的名词。


4)总的来说,此配置的意义为,客户端发出的verb类型为“*”的请求(任意类型请求) ,请求的路径格式为“cgi/*”,那么在服务器端会由UrlChangeHandler类进行处理。

Url重写的类可以写成Dll,当需要Url重写时将该Dll引入,并且在web.config进行配置即可实现。

下面我们来实现我们的处理类:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;

namespace MyHttpHandler
{
    public class UrlChangeHandler : IHttpHandler
    {
        #region IHttpHandler Members
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Path.IndexOf("aspx") != -1)
            {
                return;
            }
            StringBuilder sbObj = new StringBuilder();
            sbObj.Append(context.Request.Path);
            sbObj.Append(".aspx?");
            sbObj.Append(context.Request.QueryString.ToString());
            string url = sbObj.ToString().Replace("cgi", "handler");
            context.Server.Transfer(url, true);
        }
        #endregion
    }
}

ProcessRequest方法有一个参数,HttpContext上下文,包含Http请求信息。


if (context.Request.Path.IndexOf("aspx") != -1)
{
       return;
}


这是对请求的路径进行判断如果是正常的请求页面不进行任何处理,比如请求的路径为“http://localhost:2868/handler/RedirectForm.aspx” 。如果请求的路径符合“cgi/*”则进行处理:

StringBuilder sbObj = new StringBuilder();
sbObj.Append(context.Request.Path);
sbObj.Append(".aspx?");
sbObj.Append(context.Request.QueryString.ToString());
string url = sbObj.ToString().Replace("cgi", "handler");
context.Server.Transfer(url, true);


用StringBuilder类对请求的路径进行重写,假设现在输入的路径为“http://localhost:2868/cgi/redirectform?uid=pxl&pwd=123456”,处理过程如下:


1)首先取得“context.Request.Path” 即“http://localhost:2868/cgi/redirectform”。


2)然后附加“.aspx”即“http://localhost:2868/cgi/redirectform.aspx”。


3)然后将传递的参数附加即“http://localhost:2868/cgi/redirectform.aspx?uid=pxl&pwd=123456”。

4)然后将路径中的“cgi”替换为“handler”即“http://localhost:2868/handler/redirectform?uid=pxl&pwd=123456”。

5)最后使用上下文的Server.Transfer在不改变浏览器中路径“http://localhost:2868/cgi/redirectform?uid=pxl&pwd=123456” 的情况下,完成对Url重写,实际转向为“http://localhost:2868/handler/redirectform?uid=pxl&pwd=123456”。