ASP.NET MVC系列:UrlRouting
1. URLRouting簡(jiǎn)介
? ? URL(Uniform Resource Locator),統(tǒng)一資源定位器,是用于完整描述Internet上的網(wǎng)頁(yè)或其他資源地址的一種標(biāo)識(shí)方法。
URL一般可以由6部分組成,格式如下:
protocol :// hostname [:port] [/path] [?parameters] [#fragment]URL各部分說(shuō)明:
protocol 協(xié)議:可以是HTTP(超文本傳輸協(xié)議)、FTP(文件傳輸協(xié)議)和HTTPS(安全超文本傳輸協(xié)議)。
hostname 主機(jī)名:指在互聯(lián)網(wǎng)中存放資源的服務(wù)器DNS主機(jī)名或IP地址。
port 端口號(hào):該選項(xiàng)是一個(gè)小于66536的正整數(shù),是各服務(wù)器或協(xié)議約定的通信端口。
path 路徑:用來(lái)表示一個(gè)Web站點(diǎn)中的目錄或文件資源的地址。
parameters 參數(shù)列表:參數(shù)形式為以=隔開(kāi)的鍵/值對(duì),多個(gè)參數(shù)之間用&連接。
fragment 信息片段:用于直接定位到頁(yè)面中的某個(gè)錨點(diǎn)標(biāo)記。
2. URLRouting與URLRewrite區(qū)別
URLRouting是一組從URL到請(qǐng)求處理程序間的映射規(guī)則,將URL映射到能夠處理業(yè)務(wù)需求的Action上。URLRouting是一個(gè)獨(dú)立的類庫(kù)System.Web.Routing.dll。
URLRouting為將URL映射到Controller的Action上,處理流程圖如下:
URLRewrite為將URL映射到具體的文件資源上,處理流程圖如下:
3. ASP.NET MVC中使用及自定義URLRouting規(guī)則
在Web.config文件中與Routing有關(guān)的的節(jié)點(diǎn):sytem.web.httpModules,system.web.httpHandlers,system.webserver.modules,system.webserver.handlers。
ASP.NET MVC應(yīng)用程序第一次啟動(dòng)時(shí),將調(diào)用Global.asax中Application_Start()方法。每個(gè)ASP.NET MVC應(yīng)用程序至少需要定義一個(gè)URLRouting來(lái)指明應(yīng)用程序如何處理請(qǐng)求,復(fù)雜的應(yīng)用程序可以包含多個(gè)URLRouting。
3.1?App_Start/RouteConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing;namespace Libing.Portal.Web {public class RouteConfig{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 });}} }Global.asax
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing;namespace Libing.Portal.Web {public class MvcApplication : System.Web.HttpApplication{protected void Application_Start(){AreaRegistration.RegisterAllAreas();RouteConfig.RegisterRoutes(RouteTable.Routes);}} }3.2 Route類
RouteCollection對(duì)象以靜態(tài)屬性的方式聲明在RouteTable的屬性Routes中,RouteCollection對(duì)象存儲(chǔ)的是Route類的實(shí)例。一個(gè)完整的Route類實(shí)例需要有URL、默認(rèn)值、約束、數(shù)據(jù)密鑰及路由處理程序等屬性。
public RouteValueDictionary Constraints { get; set; } public RouteValueDictionary DataTokens { get; set; } public RouteValueDictionary Defaults { get; set; } public IRouteHandler RouteHandler { get; set; } public string Url { get; set; }3.3 Route類屬性
name:
路由名稱,必須是唯一不能重復(fù)。
url:
在Route類中,屬性URL是一個(gè)字符串,用于描述請(qǐng)求中URL的格式。該字符串可能不完全是一個(gè)實(shí)際的URL,可以帶一些{}標(biāo)記的占位符,使用占位符可以從URL中提取數(shù)據(jù)。如:
{controller}參數(shù)的值用于實(shí)例化一個(gè)處理請(qǐng)求的控制類對(duì)象,{action}參數(shù)的值用于指明處理當(dāng)前請(qǐng)求將調(diào)用控制器中的方法。
defaults:
new { controller = "Home", action = "Index", id = UrlParameter.Optional }constraints:
new { controller = @"^\w+", action = @"^\w+", id = @"\d+" }namespaces:
Route.DataTokens屬性,獲取或設(shè)置傳遞到路由處理程序但未用于確定該路由是否匹配 URL 模式的自定義值。
3.4 自定義URLRouting規(guī)則
分頁(yè):
routes.MapRoute("Page",
"{controller}/List/Page/{page}",
new { controller = "Home", action = "List", page = UrlParameter.Optional },
new { page = @"\d*" }
); public string List(int? page)
{
return page == null ? "1" : page.ToString();
}
本地化多語(yǔ)言Routing:
public static void RegisterRoutes(RouteCollection routes) {routes.IgnoreRoute("{resource}.axd/{*pathInfo}");// 本地化 routes.MapRoute(name: "Localization",url: "{lang}/{controller}/{action}/{id}",defaults: new { lang = "zh-CN", controller = "Home", action = "Index", id = UrlParameter.Optional },constraints: new { lang = "^[a-zA-Z]{2}(-[a-zA-Z]{2})?$" });routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); }分頁(yè)Routing:
routes.MapRoute(name: "PagedList",url: "{controller}/Page/{page}",defaults: new { controller = "Product", action = "Index" },constraints: new { page = @"\d+" } );Blog根據(jù)日期Routing:
routes.MapRoute(name: "blog",url: "blog/{user}/{year}/{month}/{day}",//defaults: new { controller = "Blog", action = "Index", day = 1 },defaults: new RouteValueDictionary{{"controller", "Blog"},{"action", "Index"},{"day", 1}},constraints: new { year = @"\d{4}", month = @"\d{1,2}", day = @"\d{1,2}" } );Reports根據(jù)年月Routing:
routes.MapRoute(name: "Reports",url: "Reports/{year}/{month}",defaults: new { controller = "Reports", action = "Index" },constraints: new { year = @"\d{4}", month = @"\d{1,2}" } );3.5 創(chuàng)建Routing約束
使用正則表達(dá)式來(lái)指定路由約束:
routes.MapRoute(name: "Product",url: "Product/{ProductID}",defaults: new { controller = "Product", action = "Details" },constraints: new { ProductID = @"\d+" } );3.6 自定義Routing約束
通過(guò)實(shí)現(xiàn)IRouteConstraint接口來(lái)實(shí)現(xiàn)自定義路由。
using System; using System.Collections.Generic; using System.Linq; using System.Web;using System.Web.Routing;namespace Libing.Portal.Web.Models.Constraints {public class LocalhostConstraint : IRouteConstraint{public bool Match(HttpContextBase httpContext,Route route,string parameterName,RouteValueDictionary values,RouteDirection routeDirection){return httpContext.Request.IsLocal;}} } routes.MapRoute(name: "Admin",url: "Admin/{action}",defaults: new { controller = "Admin" },constraints: new { isLocal = new LocalhostConstraint() } );自定義瀏覽器訪問(wèn)Routing約束:
using System; using System.Collections.Generic; using System.Linq; using System.Web;using System.Web.Routing;namespace Libing.Portal.Web.Models.Constraints {public class UserAgentConstraint:IRouteConstraint{private string _userAgent;public UserAgentConstraint(string userAgent){_userAgent = userAgent;}public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection){return httpContext.Request.UserAgent != null && httpContext.Request.UserAgent.Contains(_userAgent);}} } routes.MapRoute(name: "Chrome",url: "{*catchall}",defaults: new { controller = "Home", action = "Index" },constraints: new { customConstraint = new UserAgentConstraint("Chrome") } );自定義用戶個(gè)人網(wǎng)址Routing:
using System; using System.Collections.Generic; using System.Linq; using System.Web;using System.Web.Routing;using Libing.Portal.Web.Models;namespace Libing.Portal.Web.Models.Constraints {public class UserConstraint : IRouteConstraint{public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection){using (PortalContext context = new PortalContext()){string userRouteValue = values["user"].ToString();var user = (from u in context.Userswhere u.UserName == userRouteValueselect u).FirstOrDefault();return user != null;}}} } routes.MapRoute(name: "User",url: "{user}/{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },constraints: new { isValidUser = new UserConstraint() } );4. 使用RouteDebugger調(diào)試URLRouting
RouteDebugger為一個(gè)獨(dú)立的類庫(kù),RouteDebug.dll,可以從網(wǎng)上下載到,使用方法如下:
1>. 添加對(duì)RouteDebug引用;
2>. Global.ascx修改
using RouteDebug;protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); // 添加RouteDebug
}
附件:RouteDebug.rar
轉(zhuǎn)載于:https://www.cnblogs.com/libingql/archive/2012/04/07/2435687.html
總結(jié)
以上是生活随笔為你收集整理的ASP.NET MVC系列:UrlRouting的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 自己的数字选择控件NumberPicke
- 下一篇: windows 7下用SaveFileD