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

2,669

Published on

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

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
2,669
On Slideshare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
48
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • How many dealt with ASP.NET and HttpHandler
  • Some historyA page is an HttpHandlerToo rigidBound to a fileThis will not work for MVC, they need to invoke Methods (Actions) in Classes (Controller)So they wanted more flexibilityFile/extension agnosticDifferent handlers (especially they needed to introduce the separation of concerns and invoking controllers on certain points “actions”)
  • When a request comes to the server, how can the app know how to handle this request?Emphasize on RouteData being passed to the handler
  • So we could be rigid, or dynamicBut how can we make programmers more interesting and harder? :P
  • At the startup of the web app
  • It’s hard to put it in steps since it’s little bit complex and wined together, but we will try
  • “To be clear, it is not that the value of id is null when nocorresponding segment is supplied; rather, the case is that an id variable is not defined”To distinguish if user sent a value or notSeparation of concerns (defaults in routing?)
  • Specific values for controllers that might share a URL patternHttp Method has nothing to do with the “post” and “get” action filters
  • Inspired by RouteDebugger created by Phil Haack
  • Last segment includes the query string, but it’s up to the IHttpHandler how to handle it
  • Don’t use fixed URL’s!Routing doesn’t understand what “controller” is or what “action” is.Explain parametersExtra values are added as aquery stringThe Html.Action method uses routing as well, it’s not a direct call
  • Reuse values of the current request URL only for segment variables that occur earlier in the URL pattern than any parameters that are supplied to the Html.ActionLink method:
  • Don’t change namespace of controller in an AreaDo use namespace priority for the general controller
  • Don’t change the order of Area registration to be after Routing
  • Because it’s the key for the MVCHttpHandlerBy: checking the orderChecking the static stringsChecking constraints if we have them
  • Before, it was hard to test Routes, now they provided HttpContextBase
  • Before, it was hard to test Routes, now they provided HttpContextBase
  • “offer” might be date as wellI am not totally enthusiast since this is not testing Routing only, it intervenes of how binding works
  • I don’t like best practicesIf external website maybe you want to follow the SEOAvoid complexityContent vs Implementation: REST or Action? if easy go RESTful, no just don’t not too longContent title’s vs ID’s: avoid ID’s in general
  • For me, sometimes Reflector is easier to navigate
  • 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
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×