ASP.NET MVC系列:UrlRouting
1. URLRouting簡介
? ? URL(Uniform Resource Locator),統一資源定位器,是用于完整描述Internet上的網頁或其他資源地址的一種標識方法。
URL一般可以由6部分組成,格式如下:
protocol :// hostname [:port] [/path] [?parameters] [#fragment]URL各部分說明:
protocol 協議:可以是HTTP(超文本傳輸協議)、FTP(文件傳輸協議)和HTTPS(安全超文本傳輸協議)。
hostname 主機名:指在互聯網中存放資源的服務器DNS主機名或IP地址。
port 端口號:該選項是一個小于66536的正整數,是各服務器或協議約定的通信端口。
path 路徑:用來表示一個Web站點中的目錄或文件資源的地址。
parameters 參數列表:參數形式為以=隔開的鍵/值對,多個參數之間用&連接。
fragment 信息片段:用于直接定位到頁面中的某個錨點標記。
2. URLRouting與URLRewrite區別
URLRouting是一組從URL到請求處理程序間的映射規則,將URL映射到能夠處理業務需求的Action上。URLRouting是一個獨立的類庫System.Web.Routing.dll。
URLRouting為將URL映射到Controller的Action上,處理流程圖如下:
URLRewrite為將URL映射到具體的文件資源上,處理流程圖如下:
3. ASP.NET MVC中使用及自定義URLRouting規則
在Web.config文件中與Routing有關的的節點:sytem.web.httpModules,system.web.httpHandlers,system.webserver.modules,system.webserver.handlers。
ASP.NET MVC應用程序第一次啟動時,將調用Global.asax中Application_Start()方法。每個ASP.NET MVC應用程序至少需要定義一個URLRouting來指明應用程序如何處理請求,復雜的應用程序可以包含多個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對象以靜態屬性的方式聲明在RouteTable的屬性Routes中,RouteCollection對象存儲的是Route類的實例。一個完整的Route類實例需要有URL、默認值、約束、數據密鑰及路由處理程序等屬性。
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:
路由名稱,必須是唯一不能重復。
url:
在Route類中,屬性URL是一個字符串,用于描述請求中URL的格式。該字符串可能不完全是一個實際的URL,可以帶一些{}標記的占位符,使用占位符可以從URL中提取數據。如:
{controller}參數的值用于實例化一個處理請求的控制類對象,{action}參數的值用于指明處理當前請求將調用控制器中的方法。
defaults:
new { controller = "Home", action = "Index", id = UrlParameter.Optional }constraints:
new { controller = @"^\w+", action = @"^\w+", id = @"\d+" }namespaces:
Route.DataTokens屬性,獲取或設置傳遞到路由處理程序但未用于確定該路由是否匹配 URL 模式的自定義值。
3.4 自定義URLRouting規則
分頁:
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();
}
本地化多語言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 }); }分頁Routing:
routes.MapRoute(name: "PagedList",url: "{controller}/Page/{page}",defaults: new { controller = "Product", action = "Index" },constraints: new { page = @"\d+" } );Blog根據日期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根據年月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 創建Routing約束
使用正則表達式來指定路由約束:
routes.MapRoute(name: "Product",url: "Product/{ProductID}",defaults: new { controller = "Product", action = "Details" },constraints: new { ProductID = @"\d+" } );3.6 自定義Routing約束
通過實現IRouteConstraint接口來實現自定義路由。
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() } );自定義瀏覽器訪問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") } );自定義用戶個人網址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調試URLRouting
RouteDebugger為一個獨立的類庫,RouteDebug.dll,可以從網上下載到,使用方法如下:
1>. 添加對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
轉載于:https://www.cnblogs.com/libingql/archive/2012/04/07/2435687.html
總結
以上是生活随笔為你收集整理的ASP.NET MVC系列:UrlRouting的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自己的数字选择控件NumberPicke
- 下一篇: 设计模式之Adapter