Asp.Net MVC<四>:路由器

來源:互聯網
上載者:User

標籤:

 

路由的核心類型基本定義於System.Web.dll中,路由機制同樣可應用與Web Forms,實現請求地址和物理檔案的分離。

web form中使用路由器的樣本路由配置
protected void Application_Start(object sender, EventArgs e){    var defaults = new RouteValueDictionary { { "name", "*" }, { "id", "*" } };    //將物理檔案路徑映射到一個路由模版上    RouteTable.Routes.MapPageRoute("", "employees/{name}/{id}","~/default.aspx",true,defaults);}
頁面
public partial class Default : System.Web.UI.Page{    protected string EmployeeId;    protected string EmployeeName;    protected void Page_Load(object sender, EventArgs e)    {        EmployeeId = this.RouteData.Values["id"] as string;        EmployeeName = this.RouteData.Values["name"] as string;    }}
<form id="form1" runat="server"><div>    EmployeeId:<%=EmployeeId %>    <br/>     EmployeeName:<%=EmployeeName %></div></form>

 

測試

訪問地址:http://localhost:65042/Default.aspx

訪問地址:http://localhost:65042/employees

訪問地址:http://localhost:65042/employees/張飛

訪問地址:http://localhost:65042/employees/張飛/001

訪問地址:http://localhost:65042/employees/張飛/001/sdfs

404報錯

ASP.NET路由註冊
RouteTable.Routes.MapPageRoute(    routeName               : "myRoute",    routeUrl                : "dirtest/{name}/{id}",    physicalFile            : "~/default.aspx",    checkPhysicalUrlAccess  : true,    defaults                : new RouteValueDictionary { { "name", "*" }, { "id", "010" } },    constraints             : new RouteValueDictionary { { "id", @"0\d{2,3}" }, { "httpMethod", new HttpMethodConstraint("GET") } },    dataTokens              : new RouteValueDictionary { { "city", "hangzhou" } });

另一種註冊方式

Route route = new Route(    url:"dirtest/{name}/{id}",    defaults: new RouteValueDictionary { { "name", "*" }, { "id", "010" } },    constraints: new RouteValueDictionary { { "id", @"0\d{2,3}" }, { "httpMethod", new HttpMethodConstraint("GET") } },    dataTokens: new RouteValueDictionary { { "city", "hangzhou" } },    routeHandler:new PageRouteHandler("~/default.aspx",true));RouteTable.Routes.Add("myRoute",route);
註冊路由忽略地址

如果設定為RouteTable.Routes.RouteExistingFiles = true;路由系統會對所有請求實施路由,但這同樣會帶來一些問題。

例如如果應用運行在整合模式下,則靜態資源的請求也會進入ASP.NET管道,於是針對靜態檔案的請求也可能會被重新導向。

RouteTable.Routes.RouteExistingFiles = true;RouteTable.Routes.Ignore("content/{filename}.css/{*pathInfo}");

通過Ignore方法來添加例外,Ignore方法的調用必需放在路由註冊之前。

直接請求現存的物理檔案

借用路由可以採用一個與路徑無關的URL訪問某個物理檔案,但如果就是希望以物理地址的方式訪問對應的物理檔案時。

RouteBase定義了一個布爾類型的屬性RouteExistingFiles,表示是否對現有物理檔案實施路由。

預設值

defaults 為路由模版中得兩個變數指定了預設值。

約束

constraints 可以為變數指定基於正則的約束,也可以指定一個RouteConstraint對象。

路由變數

在Route對象的DataTokens屬性中可添加路由變數

根據路由規則產生URL

通過RouteCollection的GetVirtualPath方法。

RequestContext requestContext = new RequestContext();requestContext.HttpContext = new HttpContextWrapper(HttpContext.Current);requestContext.RouteData = this.RouteData;RouteValueDictionary values = new RouteValueDictionary { { "name", "劉備" }, { "id", "013" } };Response.Write("<br>");Response.Write(RouteTable.Routes.GetVirtualPath(requestContext, values).VirtualPath);Response.Write("<br>");Response.Write(RouteTable.Routes.GetVirtualPath(requestContext, null).VirtualPath);Response.Write("<br>");Response.Write(RouteTable.Routes.GetVirtualPath(null, null).VirtualPath);

MVC路由

MapPageRoute方法和Ignore方法的調用可以完成針對某個物理檔案的路由。返回的RouteData中的RouteHander屬性會返回一個PageRouteHandler對象。PageRouteHandler對象最終會建立一個針對映射.aspx檔案的Page對象來處理請求。

而MVC為RouteCollection增加了一系列擴充方法,定義在System.Web.Mvc.RouteCollectionExtensions中。新增了兩組方法 MapRoute和IgnoreRoute。

MapRoute方法不能直接添加變數到DataTokens,但可以限定路由匹配的範圍:Controller所在的命名空間。它返回的RouteData中的RouteHander屬性會返回一個MvcRouteHandler對象

UrlParameter.Optional

將變數的預設值設定為UrlParameter.Optional,則只有請求URL中真正包含具體變數值的情況下產生的RouteData的Values屬性中才會包含相應的路由變數。

基於Area的路由映射

通過Area可以從功能上將應用劃分為幾個較小的單元。每個Area相當於一個獨立的子系統。特悶具有一套包含Models,Views,Controllers在內的目錄結構和設定檔。每個路由結構一般也會具有各自獨立的路由規則,通過AreaRegistration類型進行註冊。

protected void Application_Start(){    //針對所有Area的註冊    AreaRegistration.RegisterAllAreas();}

 

RegisterAllAreas方法執行時,所有被當前Web應用直接或間接引用的程式集都會被載入(如果尚未被載入),ASP.NET MVC會從中找到所有繼承自AreaRegistration的類型,並通過反射建立相應的對象。針對每個被建立出來的AreaRegistration對象,一個作為Area註冊內容相關的AreaRegistrationContext對象會被建立出來,作為參數調用AreaRegistration對象的RegisterArea方法對相應的Area的路由進行註冊。
context.State來自AreaRegistration.RegisterAllAreas方法指定的參數state。

public class adminAreaRegistration : AreaRegistration {    public override string AreaName     {        get         {            return "admin";        }    }    public override void RegisterArea(AreaRegistrationContext context)     {        context.MapRoute(           name: "admin_default",           url: "admin/{controller}/{action}/{id}",           defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }        );    }}

  

當存在相同的控制器和方法名時,如域Area中也定義了一個Home控制器並在其內聲明了一個Index方法,則全域路由器會因為重複匹配而報錯。需要對其添加命名空間限制。

public static void RegisterRoutes(RouteCollection routes){    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");    routes.MapRoute(        name: "Default",        url: "{controller}/{action}/{id}",        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },        namespaces: new string[] { "WebApplication1.Controllers.*" }    );}

 

AreaRegistration註冊的路由對象

由AreaRegistration註冊的路由對象產生的RouteData的不同之處主要反映在DataTokens屬性上,預設多出兩個變數:

area標記Area的名稱,

UseNamespaceFallback: 當MapRoute方法顯式地指定了命名空間或者對應的AreaRegistration定義在某個命名空間下,則UseNamespaceFallback為False,反之則被設定為True。

如果MapRoute方法顯式地指定了命名空間,則AreaRegistration類型所在的命名空間也會被忽略。

MVC中產生URL的捷徑

MVC則定義了兩個協助類: HtmlHelper 和UrlHelper,通過調用它們的ActionLink/RouteLink 和Action/RouteUrl方法產生Url。從本質上講,最終依賴於RouteCollection對象的GetVirtualPathData方法。

Action、ActionLink

UrlHelper.Action(……)返回相對位址或絕對位址,HtmlHelper.ActionLink(……) 則不僅僅返回一個Url,而是產生一個連結(<a>……</a>)。

調用的是GetVirtualPathData(RequestContext requestContext,RouteValueDictionary values)方法。 也就是使用路由表中第一個匹配的Route對象來產生URL或者連結。

RouteUrl、RouteLink 

UrlHelper.RouteUrl(……)方法和HtmlHelper.RouteLink (……) 方法則可以針對註冊的某個具體的Route對象來產生URL或者連結。也即是調用GetVirtualPathData(RequestContext requestContext,string name,RouteValueDictionary values)方法。

特性路由

特性路由是對現有路由系統的擴充,提供了一種針對某個具體Controller類型或Action方法的路由註冊方式。從而可以對路由規則進行細粒度的設計。

特性路由(Attribute Route)就是利用標註在Controller類型或Action方法上的特性來提供路由規則的路由註冊方式。

註冊

預設情況下特性路由功能是關閉的,需要調用RouteCollection的擴充方法MapMvcAttributeRoutes來開啟。

要放在路由註冊之前

protected void Application_Start(){    RouteTable.Routes.MapMvcAttributeRoutes();    AreaRegistration.RegisterAllAreas();    RouteConfig.RegisterRoutes(RouteTable.Routes);}

  

public class MoviesController : Controller{    // GET: Movies    public ActionResult Index()    {        return View();    }    [HttpGet]    [Route("movies/{id}")]    public ActionResult GetMoviesById(string id)    {        ViewBag.id = id;        return View();    }    [HttpGet]    [Route("movies/starring/{starring}")]    [Route("movies/starring/{starring}/{genre}")]    [Route("movies/director/{director}/{genre}")]    public ActionResult FindMovies(string starring, string director, string genre)    {        ViewBag.starring = starring;        ViewBag.director = director;        ViewBag.genre = genre;        return View();    }}

  

預設情況下使用屬性類別型RouteAttribute,它實現了介面IRouteInfoProvider。

//// 摘要://     Provides information for building a System.Web.Routing.Route.public interface IRouteInfoProvider{    //    // 摘要:    //     Gets the name of the route to generate.    //    // 返回結果:    //     The name of the route to generate.    string Name { get; }//    // 摘要:    //     Gets the route template describing the URI pattern to match against.    //    // 返回結果:    //     The route template describing the URI pattern to match against.    string Template { get; }}

當使用RouteAttribute時,需要提供一個路由模版來對Template這個唯讀屬性進行初始化。而如果需要用這個路由特性註冊的路由對象來產生URL,還需要為它提供一個Name,以便可以從路由表中把它提取出來。

為特性路由的變數添加約束

路由變數基本都會直接綁定到目標Action方法相應的參數上,由於這些變數值在請求URL中以字串的形式體現,所以被綁定參數必需支援源自字串的類型轉換。

為了確保參數綁定的正常進行,需要對路由變數在資料類型上進行約束。這些約束可以直接以內聯的形式定義在路由模版裡

[HttpGet][Route("movies/{id:range(20,50)}")]public ActionResult GetMoviesById(int id)

對於路由系統來說,約束通過RouteContraint對象來表示,所有RouteContraint類型均實現了IRouteContraint介面。

如前面提到的特性路由可以將對某路由變數的約束直接以內聯的形式定義在路由模版中,這些約束類型,如資料類型、資料值範圍及字串長度等也是實現了IRouteContraint介面。

 

系統提供的約束
約束 描述 用法 類型
bool 類型匹配 (布爾類型) {x:bool} BoolRouteContraint
datetime 類型匹配 (DateTime類型) {x:datetime} DateTimeRouteContraint
decimal 類型匹配 (Decimal類型) {x:decimal} DecimalRouteContraint
double 類型匹配 (Double類型) {x:double} DoubleRouteContraint
float 類型匹配 (Float類型) {x:float} FloatRouteContraint
guid 類型匹配 (Guid類型) {x:guid} GuidRouteContraint
int 類型匹配 (32位整數) {x:int} IntRouteContraint
long 類型匹配 (64位整數) {x:long} LongRouteContraint
alpha 字元組成(必須有拉丁字母組成) {x:alpha} AlphaRouteContraint
regex 字元組成(必須與指定的正則匹配) {x:regex(^\d{3}-\d{3}-\d{4}$)} RegexRouteContraint
max 值範圍(小於或等於指定的最大值) {x:max(20)} MaxRouteContraint
min 值範圍(大於或等於指定的最小值) {x:max(20)} MinRouteContraint
range 值範圍(在指定的最大值和最小值之間) {x:range(20,50)} RangeRouteContraint
maxlength 字串長度(小於或等於指定的最大長度) {x:maxlength(20)} MaxLengthRouteContraint
minlength 字串長度(大於或等於指定的最小長度) {x:minlength(20)} MinlengthRouteContraint
length 字串長度(等於指定的長度或者在指定的範圍內) {x:length(6)} LengthRouteContraint

為路由變數設定預設值

1.將對應的參數定義為可預設參數

[HttpGet][Route("movies/language/{language?}")]public ActionResult GetMoviesByLanguage(string language = "en"){    return View();}

2.將預設值定義在路由模版中

[HttpGet][Route("movies/language/{language=en}")]public ActionResult GetMoviesByLanguage(string language){    return View();}
設定模版首碼

使用RoutePrefixAttribute類型的特性,它只有一個唯讀屬性Prefix,表示目標Controller所有Action方法共用的URL首碼。這個屬性只能應用在Controller類型上,且只能有一個。

[RoutePrefix("movies")]public class MoviesController : Controller{    [HttpGet]    [Route("{id:range(20,50)}")]    public ActionResult GetMoviesById(int id)    {        ViewBag.id = id;        return View();    }    [HttpGet]    [Route("starring/{starring}")]    [Route("starring/{starring}/{genre}")]    [Route("director/{director}/{genre}")]    public ActionResult FindMovies(string starring, string director, string genre)    {        ViewBag.starring = starring;        ViewBag.director = director;        ViewBag.genre = genre;        return View();    }    [HttpGet]    [Route("~/actors/{criteria}")] //使用“~”為首碼,屏蔽掉Controller類型上的首碼“movies”    public ActionResult FindActors(string criteria)    {        return View();    }}
設定Area名

使用RouteAreaAttribute類型的特性,它由兩個屬性AreaName和AreaPrefix,預設情況下使用AreaName做模版首碼,如果希望具有一個不同於Area名稱的首碼,則要通過設定AreaPrefix屬性來實現。

如果沒有使用字元“~”首碼,特性路由的完整格式為{AreaPrefix}/{RoutePrefix}/{Template} 或者{AreaName}/{RoutePrefix}/{Template} 。

[RouteArea("MoviesArea")]//[RouteArea()][RoutePrefix("movies")]public class MoviesController : Controller{    [HttpGet]    [Route("{id:range(20,50)}")]    public ActionResult GetMoviesById(int id)    {        ViewBag.id = id;        return View();    }    [HttpGet]    [Route("starring/{starring}")]    [Route("starring/{starring}/{genre}")]    [Route("director/{director}/{genre}")]    public ActionResult FindMovies(string starring, string director, string genre)    {        ViewBag.starring = starring;        ViewBag.director = director;        ViewBag.genre = genre;        return View();    }    [HttpGet]    [Route("~/admin/actors/{criteria}")] //使用“~”為首碼,屏蔽掉Controller類型上的首碼“movies”    public ActionResult FindActors(string criteria)    {        return View();    }}
自訂約束

 約束是以內聯運算式的形式定義在路由模版裡的,ASP.NET MVC通過一個實現IInlineConstraintResolver介面的對象來完成約束從字串運算式到RouteConstraint對象之間的轉換。

 系統提供的這個解析類型是DefaultInlineConstraintResolver。

public class MyInlineConstraintResolver : IInlineConstraintResolver{    public IDictionary<string, Type> ConstraintMap { get; private set; }    public MyInlineConstraintResolver()    {        this.ConstraintMap = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);        this.ConstraintMap.Add("bool", typeof(BoolRouteConstraint));        this.ConstraintMap.Add("datetime", typeof(DateTimeRouteConstraint));        this.ConstraintMap.Add("decimal", typeof(DecimalRouteConstraint));        this.ConstraintMap.Add("double", typeof(DoubleRouteConstraint));        this.ConstraintMap.Add("float", typeof(FloatRouteConstraint));        this.ConstraintMap.Add("guid", typeof(GuidRouteConstraint));        this.ConstraintMap.Add("int", typeof(IntRouteConstraint));        this.ConstraintMap.Add("long", typeof(LongRouteConstraint));        this.ConstraintMap.Add("minlength",typeof(MinLengthRouteConstraint));        this.ConstraintMap.Add("maxlength",typeof(MaxLengthRouteConstraint));        this.ConstraintMap.Add("length", typeof(LengthRouteConstraint));        this.ConstraintMap.Add("min", typeof(MinRouteConstraint));        this.ConstraintMap.Add("max", typeof(MaxRouteConstraint));        this.ConstraintMap.Add("range", typeof(RangeRouteConstraint));        this.ConstraintMap.Add("alpha", typeof(AlphaRouteConstraint));        this.ConstraintMap.Add("regex", typeof(RegexRouteConstraint));    }    public IRouteConstraint ResolveConstraint(string inlineConstraint)    {        string[] split = inlineConstraint.Split(‘(‘);        string type = split[0];        string argumentList = split.Length > 1 ? split[1].Trim().TrimEnd(‘)‘) : "";        Type constraintType;        if (this.ConstraintMap.TryGetValue(type, out constraintType))        {            split = string.IsNullOrEmpty(argumentList)? new string[0] : argumentList.Split(‘,‘);            ConstructorInfo[] constructors =(from c in constraintType.GetConstructors()                 where c.GetParameters().Count() == split.Length                 select c).ToArray();            if (constructors.Length != 1)            {                throw new InvalidOperationException("找不到與指定參數匹配的建構函式");            }            ConstructorInfo constructor = constructors[0];            ParameterInfo[] parameters = constructor.GetParameters();            object[] arguments = new object[parameters.Length];            for (int i = 0; i < parameters.Length; i++)            {                arguments[i] = Convert.ChangeType(split[i],parameters[i].ParameterType);            }            return (IRouteConstraint)constructor.Invoke(arguments);        }        return null;    }}
static void Main(string[] args){    string[] inlineConstraints = new string[]{    "bool","datetime", "decimal","double","float","guid","int",    "long","alpha", @"regex(^\d{3}-\d{7}$)","max(50)","min(10)","range(10,50)","maxlength(50)","minlength(10)","length(10,50)"};    MyInlineConstraintResolver constraintResolver = new MyInlineConstraintResolver();    IDictionary<string, IRouteConstraint> constraints = inlineConstraints.ToDictionary(inlineConstraint => inlineConstraint, inlineConstraint => constraintResolver.ResolveConstraint(inlineConstraint));    Console.WriteLine("{0,-24}{1}", "Expression", "RouteConstraint");    foreach (var item in constraints)    {        Console.WriteLine("{0,-24}{1}", item.Key,        item.Value.GetType().Name);    }    Console.ReadKey();}

Asp.Net MVC<四>:路由器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.