使用HttpModule实现程序级的URL映射

使用HttpModule实现程序级的URL映射

http://blog.csdn.net/ghostbear/article/details/6076568

原创 2010年12月14日 23:01:00

    实现原理:

           将映射机制保存在web.config文件中,并在httpmodule中添加逻辑:判断当前请求的URL是否符合映射机制,符合就映射,不符合就忽略。

     涉及的相关知识:

                IHttpMoudle的实现,正则表达式的使用,如何从web.config文件中获取自己存放的信息

    代码:

    

[c-sharp] view plain copy
 
  1. using System;  
  2. using System.Configuration;  
  3. using System.Xml;  
  4. using System.Collections;  
  5.   
  6. /// <summary>  
  7. /// ReWritingConfigurationSetHandler 的摘要说明  
  8. /// </summary>  
  9. public class ReWritingConfigurationSetHandler:IConfigurationSectionHandler  
  10. {  
  11.     static Hashtable urlMappingTable = new Hashtable();  
  12.     public ReWritingConfigurationSetHandler()  
  13.     {  
  14.         //  
  15.         // TODO: 在此处添加构造函数逻辑  
  16.         //  
  17.     }  
  18.  
  19.     #region IConfigurationSectionHandler 成员  
  20.   
  21.     object IConfigurationSectionHandler.Create(object parent, object configContext, System.Xml.XmlNode section)  
  22.     {  
  23.         XmlNode node = section.SelectSingleNode("Urls");  
  24.         foreach (XmlNode childNode in node.ChildNodes)  
  25.         {  
  26.             string fromUrl, toUrl;  
  27.             fromUrl = childNode.SelectSingleNode("From").InnerText;  
  28.             toUrl = childNode.SelectSingleNode("To").InnerText;  
  29.             urlMappingTable.Add(fromUrl, toUrl);  
  30.         }  
  31.         return urlMappingTable;  
  32.   
  33.     }  
  34.     public static Hashtable GetUrlMappingTable  
  35.     {  
  36.         get {  
  37.             return (Hashtable)System.Configuration.ConfigurationSettings.GetConfig("UrlReWriting");  
  38.         }  
  39.         set {  
  40.             urlMappingTable = value;  
  41.         }  
  42.     }  
  43.  
  44.     #endregion  
  45. }  

 

     这段代码的主要功能是获取存储在web.config文件中的映射信息

   

[c-sharp] view plain copy
 
  1. using System;  
  2. using System.Web;  
  3. using System.Collections;  
  4. using System.Text.RegularExpressions;  
  5. using System.Text;  
  6.   
  7.   
  8. /// <summary>  
  9. /// ReWritingModel 的摘要说明  
  10. /// </summary>  
  11. public class ReWritingModel:IHttpModule  
  12. {  
  13.     private HttpApplication httpApp = null;  
  14.     private Hashtable UrlMappingTable = null;  
  15.     public ReWritingModel()  
  16.     {  
  17.         //  
  18.         // TODO: 在此处添加构造函数逻辑  
  19.         //  
  20.     }  
  21.  
  22.     #region IHttpModule 成员  
  23.   
  24.     void IHttpModule.Dispose()  
  25.     {  
  26.         throw new Exception("The method or operation is not implemented.");  
  27.     }  
  28.   
  29.     void IHttpModule.Init(HttpApplication context)  
  30.     {  
  31.         this.httpApp = context;  
  32.         context.BeginRequest += new EventHandler(context_BeginRequest);  
  33.     }  
  34.   
  35.     void context_BeginRequest(object sender, EventArgs e)  
  36.     {  
  37.                UrlMappingTable = ReWritingConfigurationSetHandler.GetUrlMappingTable;  
  38.         string OriginalUrl = httpApp.Context.Request.Path;  
  39.         string pattern = null;  
  40.           
  41.          
  42.       foreach (Object key in UrlMappingTable.Keys)  
  43.       {  
  44.           pattern = key.ToString();  
  45.           Match match = Regex.Match(OriginalUrl, pattern,RegexOptions.IgnoreCase|RegexOptions.IgnorePatternWhitespace);  
  46.           String desitional = string.Empty;  
  47.             
  48.           if (match.Success)  
  49.           {  
  50.               desitional = UrlMappingTable[key].ToString();  
  51.               for (int i = 1; i < match.Groups.Count; i++)  
  52.               {  
  53.                  desitional=desitional.Replace("$" + i, match.Groups[i].ToString());  
  54.               }  
  55.               httpApp.Context.RewritePath(desitional);  
  56.   
  57.   
  58.           }  
  59.       }  
  60.        
  61.   
  62.     }  
  63.  
  64.     #endregion  
  65. }  

 

    这段代码实现了IHttpModule接口,在每次发起页面请求的时候判断请求的URL信息,并决定是否进行映射。

   

[xhtml] view plain copy
 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="test" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml" >  
  6. <head runat="server">  
  7.     <title>无标题页</title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <asp:Label ID="Label1" runat="server" Text="test"></asp:Label<br />  
  13.         <href="new_1dfdsafsd8_2erervbf12336.html" mce_href="new_1dfdsafsd8_2erervbf12336.html">new_18_236.html</a>  
  14.         </div>  
  15.     </form>  
  16. </body>  
  17. </html>  
 

 

   测试的aspx页面A

 

[xhtml] view plain copy
 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="hasParametersUrlRewriting.aspx.cs" Inherits="hasParametersUrlRewriting" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml" >  
  6. <head runat="server">  
  7.     <title>无标题页</title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.       
  13.     </div>  
  14.     </form>  
  15. </body>  
  16. </html>  

 

测试的aspx页面B

 

[xhtml] view plain copy
 
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Collections;  
  5. using System.Web;  
  6. using System.Web.Security;  
  7. using System.Web.UI;  
  8. using System.Web.UI.WebControls;  
  9. using System.Web.UI.WebControls.WebParts;  
  10. using System.Web.UI.HtmlControls;  
  11. using System.Collections.Specialized;  
  12.   
  13. public partial class hasParametersUrlRewriting : System.Web.UI.Page  
  14. {  
  15.     protected void Page_Load(object sender, EventArgs e)  
  16.     {  
  17.        //NameValueCollection param = Request.QueryString;  
  18.        Response.Write("共有" + Request.QueryString.Count + "个参数<br/>");  
  19.        Response.Write("它们为:");  
  20.        foreach (string param in Request.QueryString)  
  21.        {  
  22.            Response.Write(param +":"+Request.QueryString[param].ToString()+ "<br/>");  
  23.        }  
  24.     }  
  25. }  

 

测试的aspx页面B的后台代码

 

[xhtml] view plain copy
 
  1. <?xml version="1.0"?>  
  2. <!--   
  3.     注意: 除了手动编辑此文件以外,您还可以使用   
  4.     Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的  
  5.      “网站”->“Asp.Net 配置”选项。  
  6.     设置和注释的完整列表在   
  7.     machine.config.comments 中,该文件通常位于   
  8.     /Windows/Microsoft.Net/Framework/v2.x/Config 中  
  9. -->  
  10. <configuration>  
  11.   <configSections>  
  12.     <section name="UrlReWriting" type="ReWritingConfigurationSetHandler,App_Code"/>  
  13.   </configSections>  
  14.     <appSettings/>  
  15.     <connectionStrings/>  
  16.     <system.web>  
  17.         <!--   
  18.             设置 compilation debug="true" 将调试符号插入  
  19.             已编译的页面中。但由于这会   
  20.             影响性能,因此只在开发过程中将此值   
  21.             设置为 true。  
  22.         -->  
  23.         <compilation debug="true"/>  
  24.         <!--  
  25.             通过 <authentication> 节可以配置 ASP.NET 使用的   
  26.             安全身份验证模式,  
  27.             以标识传入的用户。   
  28.         -->  
  29.         <authentication mode="Windows"/>  
  30.         <!--  
  31.             如果在执行请求的过程中出现未处理的错误,  
  32.             则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,  
  33.             开发人员通过该节可以配置  
  34.             要显示的 html 错误页  
  35.             以代替错误堆栈跟踪。  
  36.   
  37.         <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">  
  38.             <error statusCode="403" redirect="NoAccess.htm" />  
  39.             <error statusCode="404" redirect="FileNotFound.htm" />  
  40.         </customErrors>  
  41.         -->  
  42.         <httpModules>  
  43.             <add name="ReWritingModel" type="ReWritingModel"/>  
  44.         </httpModules>  
  45.      
  46.     </system.web>  
  47.   <UrlReWriting>  
  48.     <Urls>  
  49.      <Url>  
  50.         <From>^/UrlReWriting/new_(/S*)_(/S*)(.html)/b</From>  
  51.         <To><!--[CDATA[/UrlReWriting/hasParametersUrlRewriting.aspx?Year=$1&Month=$2]]--></To>  
  52.       </Url>  
  53.        
  54.     </Urls>  
  55.   </UrlReWriting>  
  56. </configuration>  

 

web.config文件信息

 

 
posted @ 2018-02-08 09:45  sky20080101  阅读(67)  评论(0)    收藏  举报