IHttpModule实现URL重写

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

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

 

在实例化HttpApplication类时会根据web.config中的配置(包括系统级和当前网站或虚拟目录级)实例化全部实现IHttpModule接口的集合,而后会将HttpApplication类的实例做为参数依次调用每一个实现了IHttpModule接口的类的实例的Init()方法,在Init方法中能够添加对请求的特殊处理。在HttpApplication中有不少事件,其中第一个事件就是BeginRequest事件,在这个事件中咱们能够对用户请求的URL进行判断,若是知足某种要求,能够按另一种方式来进行处理。web


  好比,当接收到的用户请求的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)。app


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

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

 

UserInfo.aspx.csoop

            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");
                }
            }

 

效果图
2010-03-17_092034 2010-03-17_092043 网站

 

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

 

二、使用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"-->而后把检查文件是否存在的勾去掉这样就能够了,若是遇到“肯定”按钮失效,能够用键盘事件编辑路径便可解决。

效果图
2010-03-17_092701 2010-03-17_092712

以上内容转自:http://www.cnblogs.com/zhangyi85/archive/2008/04/20/1161826.html

注意

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

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

可解决。

 

三、修改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"]);
            }

 

效果图


2010-03-17_100637 2010-03-17_101350

 

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 ..的重写,彻底能够解决问题。

相关文章
相关标签/搜索