ASP.NET使用UrlRewriter重写URL

来源:互联网 发布:哲学原声软件 编辑:程序博客网 时间:2024/05/27 14:13

ASP.NET使用UrlRewriter重写URL,实现伪静态功能。

1、 创建/xml/URLRewriterSettings.xml文件

<?xml version="1.0" encoding="utf-8" ?><URLRewriters>  <URLRewriters Path="/product/dtl_(.*)_(.*).html" RealPath="/product/detail.aspx?ProductId=$1&CategoryNo=$2"/>  <URLRewriters Path="/product/dtl_(.*).html" RealPath="/product/detail.aspx?ProductId=$1"/>  <URLRewriters Path="/product/index.html" RealPath="/product/index.aspx"/>  <URLRewriters Path="/product/(.*).html" RealPath="/product/index.aspx?pi=$1"/></URLRewriters>

注意:该xml文件中参数多的节点要放在参数少的节点上面。

2、在App_Code目录下创建UrlRewriter.cs类

using System;using System.Data;using System.Configuration;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Web.SessionState;using System.IO;using System.Text;/// <summary>///UrlRewriter 的摘要说明/// </summary>public class UrlRewriter : IHttpHandler, IRequiresSessionState{    public UrlRewriter()    {        //        //TODO: 在此处添加构造函数逻辑        //    }    public void ProcessRequest(HttpContext Context)    {        //取得原始URL屏蔽掉参数        string Url = Context.Request.RawUrl;        int wIndex = Url.IndexOf("?");        string strLink = Url;        string strParam = string.Empty;        if (wIndex > 0)        {            strLink = Url.Substring(0, wIndex);            strParam = Url.Substring(wIndex);        }        // 如果域名中含有大写,则直接跳转到小写地址        if (System.Text.RegularExpressions.Regex.IsMatch(strLink, "[A-Z]"))        {            Context.Response.AddHeader("Location", strLink.ToLower() + strParam);            Context.Response.BufferOutput = true;            Context.Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));            Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);            Context.Response.AppendHeader("Pragma", "No-Cache");            Context.Response.StatusCode = 301;            Context.Response.Status = "301 Moved Permanently";            Context.Response.End();            return;        }        bool IsHave = false;        System.Xml.XmlDocument Dom = new System.Xml.XmlDocument();        Dom.Load(HttpContext.Current.Server.MapPath(@"~/xml/URLRewriterSettings.xml"));        System.Xml.XmlNodeList ItemList = Dom.SelectSingleNode(@"//URLRewriters").ChildNodes;        foreach (System.Xml.XmlNode Node in ItemList)        {            String Ph = Node.Attributes.GetNamedItem(@"Path").InnerText;            String Rh = Node.Attributes.GetNamedItem(@"RealPath").InnerText;            if (Ph.StartsWith(@"~")) Ph = HttpContext.Current.Request.ApplicationPath + Ph.Substring(1);            if (Rh.StartsWith(@"~")) Rh = HttpContext.Current.Request.ApplicationPath + Rh.Substring(1);            //建立正则表达式            System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex(Ph, System.Text.RegularExpressions.RegexOptions.IgnoreCase);            System.Text.RegularExpressions.Match m = Reg.Match(Url);//匹配            if (m.Success)//成功            {                if (Context.Request.QueryString.Count > 0 && Context.Request.QueryString.ToString().IndexOf(".html") >= 0)                {                    bool isParameter = false;                    for (int z = 0; z < Context.Request.QueryString.Count; z++)                    {                        if (Context.Request.QueryString[z] == m.Value)                        {                            isParameter = true;                            break;                        }                    }                    if (isParameter)                    {                        continue;                    }                }                IsHave = true;                for (int i = 1; i <= m.Groups.Count; i++)                {                    string sValue = m.Groups[i].Value;                    int index = Rh.IndexOf("$" + i.ToString());   //找到要替换参数的位置                    int len = ("$" + i.ToString()).Length;                    if (index >= 0)                    {                        string strBefore = Rh.Substring(0, index);  //要替换的字符串前面的字符串部分                        string strChange = Rh.Substring(index, len).Replace("$" + i.ToString(), sValue);  //替换要替换的字符串                        string strAfter = Rh.Substring(index + len);    //要替换的字符串前面的字符串后面部分                        Rh = strBefore + strChange + strAfter;                    }                }                if (!string.IsNullOrEmpty(Context.Request.Url.Query))                {                    if (Rh.IndexOf("?") > 0)                        Rh = Rh + "&" + Context.Request.QueryString;                    else                        Rh = Rh + "?" + Context.Request.QueryString;                }                Context.Server.Execute(Rh);                Context.Response.End();                break;            }        }        try        {            if (IsHave)            {                Context.Server.Execute(Context.Request.Url.PathAndQuery);            }            else            {                string mpath = Context.Request.PhysicalPath;                if (File.Exists(mpath))                {                    StreamReader sr = new StreamReader(mpath, System.Text.Encoding.Default);                    string str = sr.ReadToEnd();                    sr.Close();                    sr.Dispose();                    Context.Response.Write(str);                    Context.Response.End();                }                else                {                    Context.Server.Execute("/error.aspx");                    Context.Response.End();                }            }        }        catch        {            //Context.Response.Write("404 ERROR!");            //Context.Response.End();        }    }    /// <summary>    /// 实现“IHttpHandler”接口所必须的成员    /// </summary>    /// <value></value>    public bool IsReusable    {        get { return false; }    }}

3、在web.config添加配置信息

<httpHandlers>  <add verb="*" path="?*.html" type="UrlRewriter"/></httpHandlers>

测试

(1)创建/product/index.aspx和/product/detail.aspx。

(2)浏览器中输入:

          /product/1.html 则实际URL为:/product/index.aspx?pi=1

          /product/dtl_12.html 则实际URL为:/product/detail.aspx?ProductId=12

         /product/dtl_12_1001003.html 则实际URL为:/product/detail.aspx?ProductId=12&CategoryNo=1001003


原创粉丝点击