先在网站根目录下建立一个config文件夹,再在此文件架下建立一个urls.config文件,这里记录url的配置信息代码如下:
<?xml version="1.0" encoding="utf-8"?>
<urls>
<rewrite name="Product"
path="/Product-{0}.aspx"
pattern = "/Product-(\d+).aspx"
page="/Product.aspx"
querystring="pid=$1" />
<rewrite name="Article"
path="/messages/{0}.html"
pattern = "/messages/(\d+).html"
page="/Article.aspx"
querystring="aid=$1" />
<rewrite name="Product"
path="/Product/{0}"
pattern = "/Product/(\d+)"
page="/Product.aspx"
querystring="pid=$1" />
<rewrite name="default"
path="/default-{0}-{1}.aspx"
pattern = "/default-(\d+)-(\d+)?.aspx"
page="/default.aspx"
querystring="id=$1^page=$2" />
</urls>
这里只写了一种规则,然后修改网站的web.config文件,修改后的代码为:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<authentication mode="Windows"/>
<httpModules>
<add type="my.Forum.HttpModule" name="HttpModule"/>
</httpModules>
<compilation debug="true"/>
</system.web>
<!--
在 Internet 信息服务 7.0 下运行 ASP.NET AJAX 需要 system.webServer
节。对早期版本的 IIS 来说则不需要此节。
-->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add type="my.Forum.HttpModule" name="HttpModule"/>
</modules>
</system.webServer>
</configuration>
本来只写一个
<httpModules>
<add type="my.Forum.HttpModule" name="HttpModule"/>
</httpModules>
就可以了,我这里写了两个主要是为了演示如何兼容IIS7 ,然后在解决方案下新建一个项目(类库),起什么名字无所谓,主要是这个项目下一定要有一个命名空间为my.Forum的类文件。
具体代码我贴出来 详细的解释我都写在注释里了。
//用到的命名空间
using System;
using System.Diagnostics;
using System.Threading;
using System.Web;
using System.Xml;
using System.Text.RegularExpressions;
using System.IO;
//注意名称空间
namespace my.Forum
{
//继承自IHttpModule接口
public class HttpModule : System.Web.IHttpModule
{
/// <summary>
/// 实现接口的Init方法
/// </summary>
/// <param name="context"></param>
public void Init(HttpApplication context)
{
//建立个委托让他执行下面的ReUrl_BeginRequest事件
context.BeginRequest += new EventHandler(ReUrl_BeginRequest);
}
/// <summary>
/// 实现接口的Dispose方法
/// </summary>
public void Dispose()
{
}
private void ReUrl_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
string requestPath = context.Request.Path.ToLower();
//SiteUrls是下面的一个类,这里大家可以重构下
foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
{
//是否找到了匹配选项
if (Regex.IsMatch(requestPath, url.Pattern, RegexOptions.None | RegexOptions.IgnoreCase))
{
string newUrl = string.Empty;
//开始替换成我们程序能读懂的url
if (GetContainCount(requestPath, "/") > 1)
{
newUrl = Regex.Replace(requestPath.Substring(context.Request.Path.IndexOf("/")),
url.Pattern, url.QueryString, RegexOptions.None | RegexOptions.IgnoreCase);
}
else
{
newUrl = Regex.Replace(requestPath.Substring(context.Request.Path.LastIndexOf("/")),
url.Pattern, url.QueryString, RegexOptions.None | RegexOptions.IgnoreCase);
}
//这里你可以输出一下看看
//context.Response.Write(url.Page + "<br>" + newUrl+"<br>");
//开始把用户便于记忆的URL替换成程序能读懂的url
context.RewritePath(url.Page, string.Empty, newUrl);
}
}
}
/// <summary>
/// 判断某个特定的字符 在一串值中出现的次数
/// </summary>
/// <param name="str"></param>
/// <param name="symbol"></param>
/// <returns></returns>
private int GetContainCount(string str,string symbol)
{
char[] chars = str.ToCharArray();
int Count = 0;
foreach (char ch in chars)
{
if (ch.ToString().Equals(symbol))
Count++;
}
return Count;
}
}
#region
public class SiteUrls
{
//定义成volatitle类型主要是为了多线程访问方便,在这个示例程序中没什么实际意义,项目大了就有用了
private static volatile SiteUrls instance = null;
string UrlsFile = HttpContext.Current.Server.MapPath("/config/urls.config");
//定义两个属性
private System.Collections.ArrayList _Urls;
public System.Collections.ArrayList Urls
{
get { return _Urls; }
set { _Urls = value; }
}
//这个就是个键植对 表害怕一点也不高深
private System.Collections.Specialized.NameValueCollection _Paths;
public System.Collections.Specialized.NameValueCollection Paths
{
get { return _Paths; }
set { _Paths = value; }
}
//构造函数
private SiteUrls()
{
Urls = new System.Collections.ArrayList();
Paths = new System.Collections.Specialized.NameValueCollection();
//以XML个数读取那CONFIG文件
XmlDocument urlconfig = new XmlDocument();
urlconfig.Load(UrlsFile);
XmlNode root = urlconfig.SelectSingleNode("urls");
foreach (XmlNode n in root.ChildNodes)
{
//XmlNodeType.Comment如果不是注释
if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "rewrite")
{
XmlAttribute name = n.Attributes["name"];
XmlAttribute path = n.Attributes["path"];
XmlAttribute page = n.Attributes["page"];
XmlAttribute querystring = n.Attributes["querystring"];
XmlAttribute pattern = n.Attributes["pattern"];
if (name != null && path != null && page != null
&& querystring != null && pattern != null)
{
Paths.Add(name.Value, path.Value);
//压进去的都是url实体类
Urls.Add(new URLRewrite(name.Value, pattern.Value, page.Value.Replace("^", "&"),
querystring.Value.Replace("^", "&")));
}
}
}
}
//用方法实例化
public static SiteUrls GetSiteUrls()
{
if (instance == null)
{
instance = new SiteUrls();
}
return instance;
}
#region url实体类
public class URLRewrite
{
#region 成员变量
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private string _Pattern;
public string Pattern
{
get { return _Pattern; }
set { _Pattern = value; }
}
private string _Page;
public string Page
{
get { return _Page; }
set { _Page = value; }
}
private string _QueryString;
public string QueryString
{
get { return _QueryString; }
set { _QueryString = value; }
}
#endregion
#region 构造函数
public URLRewrite(string name, string pattern, string page, string querystring)
{
_Name = name;
_Pattern = pattern;
_Page = page;
_QueryString = querystring;
}
#endregion
}
#endregion
}
#endregion
}