ASP.NET Routing & MVC

34
Emad Alashi ASP.NET/IIS MVP Jordev Readify www.DotNetArabi.com www.EmadAshi.com @emadashi

description

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

Transcript of ASP.NET Routing & MVC

Page 1: ASP.NET Routing & MVC

Emad AlashiASP.NET/IIS MVP

Jordev

Readify

www.DotNetArabi.com

www.EmadAshi.com

@emadashi

Page 2: ASP.NET Routing & MVC

URL Routing & MVCALL YOUR URL ARE BELONG TO YOU!

Page 3: ASP.NET Routing & MVC

Agenda• Why understanding Routing is important

• What is Routing?

• How it works

• How to test it

• Best Some practices

Page 4: ASP.NET Routing & MVC

Why understanding Routing• The entry to your web app

• HyperTextTransferProtol

• Strongly relates to Binding

• Never stay in doubt

Page 5: ASP.NET Routing & MVC

What is URL Routing

Page 6: ASP.NET Routing & MVC

History/store/products.aspx?key=value

Store

Products.aspx

Page life cycle

QueryString[“..”]

Page 7: ASP.NET Routing & MVC

HandlersStore/products/apples

• Parse

• Extract variables

• Route to Handler URL

MVCHttpHandler

OtherHttpHandler

Emad _
Make sure this is so for all the handlers
Page 8: ASP.NET Routing & MVC

HandlersOptions?

• 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

Page 9: ASP.NET Routing & MVC

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"} );

Page 10: ASP.NET Routing & MVC

How URL Routing works

Page 11: ASP.NET Routing & MVC

Segmentation

http://store.com/home/index

First segment Second segment

Page 12: ASP.NET Routing & MVC

Static words

“{controller} /{action}”

“home/index”

“anything/willdo”

=============================

“abc{controller} / {action}”

“abchome / whatever”

==================

“abc{controller} / {action}”

“home / whatever”

Page 13: ASP.NET Routing & MVC

RouteData.Values“{controller}/{action}/{id}”

“product/index/3”

Variable value

controller Product

action Index

id 3

Page 14: ASP.NET Routing & MVC

DefaultsOr Defaults:

“product/index” ?

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { id=3 }

);

Variable Value

controller Product

action Index

id !

Variable Value

controller Product

action Index

Id 3

Page 15: ASP.NET Routing & MVC

UrlParameter.Optionalroutes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new {action = "Index“, id=UrlParameter.Optinal}

);

• Supplied: “product/index/3”

• Not supplied:“product/index”

Variable value

controller Product

action Index

id 3

Variable value

controller Product

action index

Page 16: ASP.NET Routing & MVC

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

Page 17: ASP.NET Routing & MVC

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)

Page 18: ASP.NET Routing & MVC

Debug Routes

Page 19: ASP.NET Routing & MVC

Notes (Incoming)• Reserved custom variables: “controller, action, area”

• routes.RouteExistingFiles = true;

• routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

• Last segment includes the QueryString

Page 20: ASP.NET Routing & MVC

How Routing works (Outgoing)

Page 21: ASP.NET Routing & MVC

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

Page 22: ASP.NET Routing & MVC

Rules

1. All variables should have values: “{controller}/{action}/{id}” a) Suppliedb) Current requestc) Default values

2. Should not dis-agree with default-only variables:

routes.MapRoute("MyRoute", "{controller}/{action}", new { myVar = "true" });

3. Satisfy constraints

Page 23: ASP.NET Routing & MVC

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

Page 24: ASP.NET Routing & MVC

Areas

Page 25: ASP.NET Routing & MVC

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 }

);

}

}

Page 26: ASP.NET Routing & MVC

AreasAreaRegistration.RegisterAllAreas();

RouteConfig.RegisterRoutes(RouteTable.Routes);

Page 27: ASP.NET Routing & MVC

Unit-Testing Routes

Page 28: ASP.NET Routing & MVC

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 variables as expected.

Page 29: ASP.NET Routing & MVC

Unit-Testing Routes (Incoming)• Incoming:

• HttpRequestBase• HttpContextBase• HttpResponseBase

• Outcoing:• +• UrlHelper

Page 30: ASP.NET Routing & MVC

Unit-Testing Routes (Incoming)

Demo

Page 31: ASP.NET Routing & MVC

Unit-Testing Routes (Incoming)

MvcContribhttp://mvccontrib.codeplex.com/

"~/Products/View/44/offer".ShouldMapTo<ProductsController>(action => action.View(44, “offer"));

Page 32: ASP.NET Routing & MVC

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

Page 33: ASP.NET Routing & MVC

ASP.NET

It’s all open source!http://aspnetwebstack.codeplex.com/

Page 34: ASP.NET Routing & MVC

Q & A

www.emadashi.com@EmadAshi