Mvc routing and mvc Routing Mechanism
1. General routing settings
1. the URL mode routing system uses a group of routes to implement its functions. These routes constitute the URL architecture or scheme of the application. Two key actions of a URL: a. The URL mode is conservative, so it only matches a URL with the same number of segments as the URL mode. B. the URL mode is loose. If a URL exactly occupies the right segment number, this mode is used to extract the value for the segment variable, regardless of the value. 2. Use static URL fragment // the Controller will add X routes. mapRoute ("", "X {controller}/{action}", new {controller = "Product", action = "Index "}); // navigation to the Store controller instead of the Product controller routes. mapRoute ("Store", "Store/{action}", new {controller = "Product"}); routes. mapRoute ("", "{controller}/{action}", new {controller = "Product", action = "Index "}); // The format of the route must start with Public. mapRoute ("", "Public/{controller}/{actio N} ", new {controller =" Product ", action =" Index "}); 3. Define the custom fragment variable/* If {id} is not included in the URL, defaultId is assigned to id */routes by default. mapRoute ("", "{controller}/{action}/{id}", new {controller = "Product", action = "Index ", id = "DefaultId"}); 4. Define an optional URL segment // The default value of id is UrlParameter. optional, indicating that the fragment variable is an Optional routes. mapRoute ("", "{controller}/{action}/{id}", new {controller = "Product", action = "Index", id = UrlParameter. option (Al); 5. Define a variable-length route/* change the URL mode. The default conservative mode is to receive variable URLs. You can define the support for variable part numbers by using a fully-matched (catchall) fragment variable with the star number (*) as its prefix. */Routes. mapRoute ("", "{controller}/{action}/{id}/{* catchall}", new {controller = "", action = "", id = UrlParameter. optional}); 6. differentiate controllers by namespace in the priority routes. mapRoute ("", "{controller}/{action}/{id}/{* catchall}", new {controller = "", action = "", id = UrlParameter. optional},/*: Let the mvc framework first find the controller in the namespace AdditionalControllers. * if no suitable controller is found, the mvc Framework will return to normal behavior by default. */New [] {"URLsAndRoutes. additionalControllers "}); disable the alternate namespace Route myRoute = routes. mapRoute ("", "{controller}/{action}/{id}/{* catchall}", new {controller = "", action = "", id = UrlParameter. optional} new [] {"URLsAndRoutes. additionalControllers "});/* indicates that the request fails if no matched control exists in the AdditionalControllers namespace. */MyRoute. DataTokens ["UseNamespaceFallback"] = false;
Ii. constraint Routing
1. Use a regular expression to constrain a route and a route to a specified group of values.
Route myRoute = routes. mapRoute ("", "{controller}/{action}/{id}/{* catchall}", new {controller = "", action = "", id = UrlParameter. optional},/* controller = "^ H. * "The regular expression is used to specify the route. It only matches the Controller starting with H. * action only matches the URL of Index or About. */New {controller = "^ H. *", action = "^ Index $ | ^ About $ "});
2. Use the HTTP Method to restrict routing
Routes. mapRoute ("", "{controller}/{action}/{id}/{* catchall}", new {controller = "", action = "", id = UrlParameter. optional},/** httpMethod only allows GET requests. */New {httpMethod = new HttpMethodConstraint ("GET")}, new [] {"URLsAndRoutes. AdditionalControllers "});
3. Use type and value Constraints
Routes. mapRoute ("", "{controller}/{action}/{id}/{* catchall}", new {controller = "", action = "", id = UrlParameter. optional},/** id is a number between 10 and 20. */New {id = new RangeRouteConstraint (10, 20)}, new [] {"URLsAndRoutes. AdditionalControllers "});
4. Define custom constraints
Public class UserAgentConstraint: IRouteConstraint {private string requiredUserAgent; public UserAgentConstraint (string agentParm) {requiredUserAgent = agentParm ;} /// <summary> /// determine whether the URL parameter contains the valid value of this constraint. /// </Summary> /// <param name = "httpContext"> an object, encapsulate HTTP Request Information </param> /// <param name = "route"> object to which this constraint belongs </param> /// <param name = "parameterName"> name of the parameter being checked </param> /// <param name = "values"> an object containing URL parameters </param> /// <param name = "routeDirection"> an object, indicates whether the constraint check is being executed when processing incoming requests or generating URLs </param> // <returns> true if the URL parameter contains a valid value; otherwise false </returns> public bool Match (HttpContextBase httpContext, Route Route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {bool flag = false; // judge and process the client's UserAgent attribute flag = httpContext. Request. UserAgent! = Null & httpContext. Request. UserAgent. Contains (requiredUserAgent); return flag ;}// only matches browser requests containing Chrome from the user's proxy string.
routes.MapRoute("", "{*cathcall}",
new { controller = "Product", action = "Index" },
new { customConstraint = new UserAgentConstraint("Chrome") },
new[] { "URLsAndRoutes.AdditionalControllers" });
3. Use attribute Routing
1. Enable and use Attribute Routing
Add routes. MapMvcAttributeRoutes () in the RegisterRoutes method to use Attribute routing. For example: // [RoutePrefix ("Homes")] // prefix. The Homes instance is added to the Url: http://localhost:11236/Homes/Home/List/11-124Public class HomeController: Controller {// GET:/Home/public ActionResult Index (int id = 8) {ViewBag. controllerName = "Home"; ViewBag. actionName = "Index"; return View () ;}// [Route ("Home/List/{id: int}-// {name}")] // http://localhost:11236/Homes/Home/List/11-124
[Route ("~ /Test ")] public ActionResult List (int id = 8) {ViewBag. controllerName = "Home"; ViewBag. actionName = "List"; // ViewBag. id = RouteData. values ["id"]; // only the {id} ViewBag defined in the route can be obtained. id = id; return View ();}}
Default mvc route: public static void RegisterRoutes (RouteCollection rotues) {routes. mapRoute ("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = Urlparameter. optional});} route without parameters: routes. mapRoute
(
"NoParameter",
"{controller}/{action}/{id}"
);
Iii. routes with namespaces
Routes. mapRoute ("AdminControllers", // route name "{controller}/{id}-{action}", // URL with parameters new {controller = "Home ", action = "Index", id = UrlParameter. optional}, // default value of the parameter new string [] {"Admin. controllers "} // namespace );
4. Routing rules with constraints (The constraint means that the regular expressions must meet the conditions.)
Routes. mapRoute ("RuleControllers", "{controller}/{action}-{Year}-{Month}-{Day}", new {controller = "Home ", action = "Index", Year = "2010", Month = "04", Day = "21"}, new {Year = @ "^ \ d {4 }", month = @ "\ d {2}"} // 4-digit 2-digit );
5. Routing rules with namespaces, constraints, and default values
routes.MapRoute( "Rule1", "Admin/{controller}/{action}-{Year}-{Month}-{Day}", new { controller = "Home", action = "Index", Year = "2010", Month = "04", Day = "21" }, new { Year = @"^\d{4}", Month = @"\d{2}" }, new string[] { "Admin.Controllers" } );
6. Capture all routes
Routes. mapRoute ("All", // route name "{* vaute}", // URL with parameters new {controller = "Home", action = "Index ", id = UrlParameter. optional} // default value );