ASP.NET Routing & MVC
-
Upload
emad-alashi -
Category
Technology
-
view
2.613 -
download
1
Embed Size (px)
description
Transcript of ASP.NET Routing & MVC

Emad AlashiASP.NET/IIS MVP
Jordev
Readify
www.DotNetArabi.com
www.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 doubt

What is URL Routing

History/store/products.aspx?key=value
Store
Products.aspx
Page life cycle
QueryString[“..”]

HandlersStore/products/apples
• Parse
• Extract variables
• Route to Handler URL
MVCHttpHandler
OtherHttpHandler

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

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

How URL Routing works

Segmentation
http://store.com/home/index
First segment Second segment

Static words
“{controller} /{action}”
“home/index”
“anything/willdo”
=============================
“abc{controller} / {action}”
“abchome / whatever”
==================
“abc{controller} / {action}”
“home / whatever”

RouteData.Values“{controller}/{action}/{id}”
“product/index/3”
Variable value
controller Product
action Index
id 3

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

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

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

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)

Debug Routes

Notes (Incoming)• Reserved custom variables: “controller, action, area”
• routes.RouteExistingFiles = true;
• routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
• Last segment includes the QueryString

How Routing works (Outgoing)

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

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

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

Areas

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

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

Unit-Testing Routes (Incoming)• Incoming:
• HttpRequestBase• HttpContextBase• HttpResponseBase
• Outcoing:• +• UrlHelper

Unit-Testing Routes (Incoming)
Demo

Unit-Testing Routes (Incoming)
MvcContribhttp://mvccontrib.codeplex.com/
"~/Products/View/44/offer".ShouldMapTo<ProductsController>(action => action.View(44, “offer"));

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

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