Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Emad AlashiASP.NET/IIS MVPJordevReadifywww.DotNetArabi.comwww.EmadAshi.com@emadashi
URL Routing & MVCALL YOUR URL ARE BELONG TO YOU!
Agenda• Why understanding Routing is important• What is Routing?• How it works• How to test it• Best Some practices
Why understanding Routing• The entry to your web app• HyperTextTransferProtol• Strongly relates to Binding• Never stay in ...
What is URL Routing
History/store/products.aspx?key=value                                     Store       Page life cycle                     ...
HandlersStore/products/apples•    Parse•    Extract variables         OtherHttpHandler•    Route to Handler    URL        ...
Handlers Options?• Rigid (absolute string comparison):   e.g. “http://store/products/view” ===> invoke method “view” in cl...
PriorityWe have to choose between patterns!           routes.MapRoute(               name: "Default",               url: "...
How URL Routingworks
Segmentation        http://store.com/home/index                   First segment   Second segment
Static words                   “,controller- /,action-”                       “home/index”                     “anything/w...
RouteData.Values  “,controller}/{action-/,id-”  “product/index/3”                                 Variable     value      ...
DefaultsOr Defaults:                                        Variable     Value     “product/index”                        ...
UrlParameter.Optional routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}",                          Variab...
No excessive number of segments          “,controller-/,action-/,id-”          “products/oranges/edit/3”Unless:          “...
Constraints 1.   Regular Expressions:      routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", …         ...
Debug Routes
Notes (Incoming)• Reserved custom variables: “controller, action, area”• routes.RouteExistingFiles = true;• routes.IgnoreR...
How Routing works   (Outgoing)
Helpers1.   Html.ActionLink(text, nameOfAction, nameOfController, RouteValues, HtmlAttributes)2.   Url.Action(text, nameOf...
Rules1.   All variables should have values: “,controller-/,action-/,id-”     a)   Supplied     b)   Current request     c)...
Notes (Outgoing)• Tricky: Reuse values of the current request URL:   url: "{controller}/{action}/{id}/{forth}",           ...
Areas
Areaspublic class AdminAreaRegistration : AreaRegistration {       public override string AreaName         { get   {      ...
AreasAreaRegistration.RegisterAllAreas();RouteConfig.RegisterRoutes(RouteTable.Routes);
Unit-Testing Routes
Unit-Testing Routes (Incoming)What do we want to test?That the url patterns we want to support in our web app would popula...
Unit-Testing Routes (Incoming)• Incoming:   •   HttpRequestBase   •   HttpContextBase   •   HttpResponseBase• Outcoing:   ...
Unit-Testing Routes (Incoming)                Demo
Unit-Testing Routes (Incoming)                                     MvcContrib                             http://mvccontri...
Design Guidelines• Content vs Implementation• Human friendly: content titles vs id’s• Hackable• Sense of hierarchy• Static...
ASP.NET       It’s all open source!     http://aspnetwebstack.codeplex.com/
Q&A      www.emadashi.com         @EmadAshi
Upcoming SlideShare
Loading in …5
×

ASP.NET Routing & MVC

3,713 views

Published on

What is ASP.NET Routing and how it relates to ASP.NET MVC

Published in: Technology
  • Be the first to comment

  • Be the first to like this

ASP.NET Routing & MVC

  1. 1. Emad AlashiASP.NET/IIS MVPJordevReadifywww.DotNetArabi.comwww.EmadAshi.com@emadashi
  2. 2. URL Routing & MVCALL YOUR URL ARE BELONG TO YOU!
  3. 3. Agenda• Why understanding Routing is important• What is Routing?• How it works• How to test it• Best Some practices
  4. 4. Why understanding Routing• The entry to your web app• HyperTextTransferProtol• Strongly relates to Binding• Never stay in doubt
  5. 5. What is URL Routing
  6. 6. History/store/products.aspx?key=value Store Page life cycle QueryString*“..”+ Products.aspx
  7. 7. HandlersStore/products/apples• Parse• Extract variables OtherHttpHandler• Route to Handler URL MVCHttpHandler
  8. 8. Handlers Options?• Rigid (absolute string comparison): e.g. “http://store/products/view” ===> invoke method “view” in class “products”• Pattern base: 1. http://store/{classX}/{methodY} ===> use MvcHttpHandler => Invoke method “Y” in class “X” 2. http://p/sub}/{module} ===> use MagicHttpHandler => invoke crazy code
  9. 9. PriorityWe have to choose between patterns! routes.MapRoute( name: "Default", url: "{controller}/{action}/", defaults: new { controller = "Home", action = "Index"} ); routes.MapRoute( name: "My2ndRoute", url: "special{awesome}Pattern/{anotherVariable}", defaults: new { awesome = "magic"} );
  10. 10. How URL Routingworks
  11. 11. Segmentation http://store.com/home/index First segment Second segment
  12. 12. Static words “,controller- /,action-” “home/index” “anything/willdo” ============================= “abc,controller- / ,action-” “abchome / whatever” ================== “abc,controller- / ,action-” “home / whatever”
  13. 13. RouteData.Values “,controller}/{action-/,id-” “product/index/3” Variable value controller Product action Index id 3
  14. 14. DefaultsOr Defaults: Variable Value “product/index” controller Product? action Index routes.MapRoute( id Id ! 3 name: "Default", url: "{controller}/{action}/{id}", defaults: new { id=3 } );
  15. 15. UrlParameter.Optional routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", Variable value defaults: new {action = "Index“, id=UrlParameter.Optinal} controller Product ); action Index id 3• Supplied: “product/index/3”• Not supplied: Variable value “product/index” controller Product action index
  16. 16. No excessive number of segments “,controller-/,action-/,id-” “products/oranges/edit/3”Unless: “,controller}/{action}/{id}/{*catchall-” “product/oranges/edit/3/something’ Variable value controller Product action Index id edit Catchall 3/something
  17. 17. Constraints 1. Regular Expressions: routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", … constraints: new { controller = "^H.*" } ); 2. Specific values: constraints: new { action = "^Index$|^About$*" } 3. HTTP methods: constraints: new { httpMethod= new HttpMethodConstraint("GET") } 4. Custom constraints: bool IRouteConstraint.Match(HttpContextBase, Route, stringParameterName, RouteValueDictionary, RouteDireciont)
  18. 18. Debug Routes
  19. 19. Notes (Incoming)• Reserved custom variables: “controller, action, area”• routes.RouteExistingFiles = true;• routes.IgnoreRoute("{resource}.axd/{*pathInfo}");• Last segment includes the QueryString
  20. 20. How Routing works (Outgoing)
  21. 21. Helpers1. Html.ActionLink(text, nameOfAction, nameOfController, RouteValues, HtmlAttributes)2. Url.Action(text, nameOfAction, nameOfController, RouteValues)3. @Html.RouteLink(text, RouteValues, HtmlAttributes)4. Url.RouteLink(text, AnonymouseTypeValues)• You can use Route name
  22. 22. Rules1. All variables should have values: “,controller-/,action-/,id-” a) Supplied b) Current request c) Default values2. Should not dis-agree with default-only variables: routes.MapRoute("MyRoute", "{controller}/{action}", new { myVar = "true" });3. Satisfy constraints
  23. 23. Notes (Outgoing)• Tricky: Reuse values of the current request URL: url: "{controller}/{action}/{id}/{forth}", defaults: new { controller = "Home", action = "Index", id = 3, forth=8},------------ @Html.ActionLink("this is the link", "Index", new {id=5 }); @Html.ActionLink("this is the link", "Index", new {forth=8 });• Url’s generated will try to produce the shortest url
  24. 24. Areas
  25. 25. Areaspublic class AdminAreaRegistration : AreaRegistration { public override string AreaName { get { return "Admin"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Admin_default", "Admin/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } }
  26. 26. AreasAreaRegistration.RegisterAllAreas();RouteConfig.RegisterRoutes(RouteTable.Routes);
  27. 27. Unit-Testing Routes
  28. 28. Unit-Testing Routes (Incoming)What do we want to test?That the url patterns we want to support in our web app would populate the RouteData variablesas expected.
  29. 29. Unit-Testing Routes (Incoming)• Incoming: • HttpRequestBase • HttpContextBase • HttpResponseBase• Outcoing: • + • UrlHelper
  30. 30. Unit-Testing Routes (Incoming) Demo
  31. 31. Unit-Testing Routes (Incoming) MvcContrib http://mvccontrib.codeplex.com/"~/Products/View/44/offer".ShouldMapTo<ProductsController>(action => action.View(44, “offer"));
  32. 32. Design Guidelines• Content vs Implementation• Human friendly: content titles vs id’s• Hackable• Sense of hierarchy• Static strings at the beggning of routes• Dash instead of underscore• Not too long• Avoid complexity• Be consistent
  33. 33. ASP.NET It’s all open source! http://aspnetwebstack.codeplex.com/
  34. 34. Q&A www.emadashi.com @EmadAshi

×