自定义实现URL重写 04.18
1、定义XML规则,配置好URL节点
?xml version="1.0" encoding="utf-8" ?> <urls> <rewrite name="ShowNews" pattern="news-(\d+).html" page="news.aspx" query="id=$1"> </rewrite> </urls>
2、对XML的解析,对其进行封装
public class MyUrlRewrite { public string Name { get; set; } public string Pattern { get; set; } public string Page { get; set; } public string Query { get; set; } } public class UrlList { private static UrlList instance; public List<MyUrlRewrite> GetAllUrls { get; set; } private UrlList() { GetAllUrls = new List<MyUrlRewrite>(); XmlDocument xmlDoc = new XmlDocument(); string xmlPath = HttpContext.Current.Request.PhysicalApplicationPath + "/UrlLink.config"; xmlDoc.Load(xmlPath); XmlNode node = xmlDoc.SelectSingleNode("urls"); foreach (XmlNode item in node.ChildNodes) { XmlAttribute name = item.Attributes["name"]; XmlAttribute pattern = item.Attributes["pattern"]; XmlAttribute page = item.Attributes["page"]; XmlAttribute query = item.Attributes["query"]; if (name == null || pattern == null || query == null || pattern == null) continue; MyUrlRewrite model = new MyUrlRewrite(); model.Name = name.Value; model.Pattern = pattern.Value; model.Page = page.Value; model.Query = query.Value; GetAllUrls.Add(model); } } public static UrlList GetUrlList() { if (instance == null) { instance = new UrlList(); } return instance; } }
3、自定义IHttpModule接口实现URL重写【关于此接口的介绍不做多讲,网上有很多】
/** * 向实现类提供模块初始化和事件处理 * */ public class MyHttpModule : System.Web.IHttpModule { #region IHttpModule 成员 //处置由实现 IHttpModule 的模块使用的资源(内存除外)。 public void Dispose() { throw new NotImplementedException(); } //初始化模块,并使其为处理请求做好准备。 public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void context_BeginRequest(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; string requestPath = context.Request.Path.ToLower(); foreach (MyUrlRewrite item in UrlList.GetUrlList().GetAllUrls) { //不区分大小写 if (Regex.IsMatch(requestPath, item.Pattern, RegexOptions.IgnoreCase)) { string newUrl = Regex.Replace(requestPath, item.Pattern, item.Query); if (newUrl.Length == 0) context.RewritePath(item.Page); else context.RewritePath(item.Page + "?" + newUrl.Substring(1)); } } } #endregion }
4、在web.config进行相应的配置
<httpModules> <add name="urlrewrite" type="_017_URL重写.MyHttpModule,017_URL重写"/> </httpModules>
5、最终的效果图
小结:
1、了解asp.net的管道和生命周期很重要
2、将程序可配置化,避免总是修改demo,采用xml定义规则
3、最重要的是:湖人进入季后赛了,但科比受伤了。
生活没有输赢,不要在乎别人如何评价你,开心就好。
QQ群:158138959