asp.net 不用組件的URL重寫(適用於較大型項目)

來源:互聯網
上載者:User

先在網站根目錄下建立一個config檔案夾,再在此檔案架下建立一個urls.config檔案,這裡記錄url的配置資訊代碼如下: 複製代碼 代碼如下:<?xml version="1.0" encoding="utf-8"?>
<urls>
<rewrite name="default"
path="/default-{0}-{1}.aspx"
pattern = "/default-(\d+)(-(\d+))?.aspx"
page="/default.aspx"
querystring="id=$1^page=$3" />
</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))
{
//開始替換成我們程式能讀懂的url
string 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);
}
}
}
}
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
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.