使用HttpModule实现程序级的URL映射
使用HttpModule实现程序级的URL映射
http://blog.csdn.net/ghostbear/article/details/6076568
实现原理:
将映射机制保存在web.config文件中,并在httpmodule中添加逻辑:判断当前请求的URL是否符合映射机制,符合就映射,不符合就忽略。
涉及的相关知识:
IHttpMoudle的实现,正则表达式的使用,如何从web.config文件中获取自己存放的信息
代码:
- using System;
- using System.Configuration;
- using System.Xml;
- using System.Collections;
- /// <summary>
- /// ReWritingConfigurationSetHandler 的摘要说明
- /// </summary>
- public class ReWritingConfigurationSetHandler:IConfigurationSectionHandler
- {
- static Hashtable urlMappingTable = new Hashtable();
- public ReWritingConfigurationSetHandler()
- {
- //
- // TODO: 在此处添加构造函数逻辑
- //
- }
- #region IConfigurationSectionHandler 成员
- object IConfigurationSectionHandler.Create(object parent, object configContext, System.Xml.XmlNode section)
- {
- XmlNode node = section.SelectSingleNode("Urls");
- foreach (XmlNode childNode in node.ChildNodes)
- {
- string fromUrl, toUrl;
- fromUrl = childNode.SelectSingleNode("From").InnerText;
- toUrl = childNode.SelectSingleNode("To").InnerText;
- urlMappingTable.Add(fromUrl, toUrl);
- }
- return urlMappingTable;
- }
- public static Hashtable GetUrlMappingTable
- {
- get {
- return (Hashtable)System.Configuration.ConfigurationSettings.GetConfig("UrlReWriting");
- }
- set {
- urlMappingTable = value;
- }
- }
- #endregion
- }
这段代码的主要功能是获取存储在web.config文件中的映射信息
- using System;
- using System.Web;
- using System.Collections;
- using System.Text.RegularExpressions;
- using System.Text;
- /// <summary>
- /// ReWritingModel 的摘要说明
- /// </summary>
- public class ReWritingModel:IHttpModule
- {
- private HttpApplication httpApp = null;
- private Hashtable UrlMappingTable = null;
- public ReWritingModel()
- {
- //
- // TODO: 在此处添加构造函数逻辑
- //
- }
- #region IHttpModule 成员
- void IHttpModule.Dispose()
- {
- throw new Exception("The method or operation is not implemented.");
- }
- void IHttpModule.Init(HttpApplication context)
- {
- this.httpApp = context;
- context.BeginRequest += new EventHandler(context_BeginRequest);
- }
- void context_BeginRequest(object sender, EventArgs e)
- {
- UrlMappingTable = ReWritingConfigurationSetHandler.GetUrlMappingTable;
- string OriginalUrl = httpApp.Context.Request.Path;
- string pattern = null;
- foreach (Object key in UrlMappingTable.Keys)
- {
- pattern = key.ToString();
- Match match = Regex.Match(OriginalUrl, pattern,RegexOptions.IgnoreCase|RegexOptions.IgnorePatternWhitespace);
- String desitional = string.Empty;
- if (match.Success)
- {
- desitional = UrlMappingTable[key].ToString();
- for (int i = 1; i < match.Groups.Count; i++)
- {
- desitional=desitional.Replace("$" + i, match.Groups[i].ToString());
- }
- httpApp.Context.RewritePath(desitional);
- }
- }
- }
- #endregion
- }
这段代码实现了IHttpModule接口,在每次发起页面请求的时候判断请求的URL信息,并决定是否进行映射。
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="test" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>无标题页</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:Label ID="Label1" runat="server" Text="test"></asp:Label> <br />
- <a href="new_1dfdsafsd8_2erervbf12336.html" mce_href="new_1dfdsafsd8_2erervbf12336.html">new_18_236.html</a>
- </div>
- </form>
- </body>
- </html>
测试的aspx页面A
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="hasParametersUrlRewriting.aspx.cs" Inherits="hasParametersUrlRewriting" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>无标题页</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- </div>
- </form>
- </body>
- </html>
测试的aspx页面B
- using System;
- using System.Data;
- using System.Configuration;
- using System.Collections;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.Collections.Specialized;
- public partial class hasParametersUrlRewriting : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- //NameValueCollection param = Request.QueryString;
- Response.Write("共有" + Request.QueryString.Count + "个参数<br/>");
- Response.Write("它们为:");
- foreach (string param in Request.QueryString)
- {
- Response.Write(param +":"+Request.QueryString[param].ToString()+ "<br/>");
- }
- }
- }
测试的aspx页面B的后台代码
- <?xml version="1.0"?>
- <!--
- 注意: 除了手动编辑此文件以外,您还可以使用
- Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
- “网站”->“Asp.Net 配置”选项。
- 设置和注释的完整列表在
- machine.config.comments 中,该文件通常位于
- /Windows/Microsoft.Net/Framework/v2.x/Config 中
- -->
- <configuration>
- <configSections>
- <section name="UrlReWriting" type="ReWritingConfigurationSetHandler,App_Code"/>
- </configSections>
- <appSettings/>
- <connectionStrings/>
- <system.web>
- <!--
- 设置 compilation debug="true" 将调试符号插入
- 已编译的页面中。但由于这会
- 影响性能,因此只在开发过程中将此值
- 设置为 true。
- -->
- <compilation debug="true"/>
- <!--
- 通过 <authentication> 节可以配置 ASP.NET 使用的
- 安全身份验证模式,
- 以标识传入的用户。
- -->
- <authentication mode="Windows"/>
- <!--
- 如果在执行请求的过程中出现未处理的错误,
- 则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
- 开发人员通过该节可以配置
- 要显示的 html 错误页
- 以代替错误堆栈跟踪。
- <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
- <error statusCode="403" redirect="NoAccess.htm" />
- <error statusCode="404" redirect="FileNotFound.htm" />
- </customErrors>
- -->
- <httpModules>
- <add name="ReWritingModel" type="ReWritingModel"/>
- </httpModules>
- </system.web>
- <UrlReWriting>
- <Urls>
- <Url>
- <From>^/UrlReWriting/new_(/S*)_(/S*)(.html)/b</From>
- <To><!--[CDATA[/UrlReWriting/hasParametersUrlRewriting.aspx?Year=$1&Month=$2]]--></To>
- </Url>
- </Urls>
- </UrlReWriting>
- </configuration>
web.config文件信息