SlideShare a Scribd company logo
Emad Alashi
ASP.NET/IIS MVP
Jordev
Readify
www.DotNetArabi.com
www.EmadAshi.com
@emadashi
URL Routing & MVC
ALL 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       Page life cycle




                                                  QueryString*“..”+
                                 Products.aspx
Handlers
Store/products/apples


•    Parse
•    Extract variables         OtherHttpHandler

•    Route to Handler    URL

                               MVCHttpHandler
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
Priority
We 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
Defaults
Or Defaults:                                        Variable     Value
     “product/index”                                controller   Product

?                                                   action       Index
     routes.MapRoute(                               id
                                                    Id           !
                                                                 3

               name: "Default",

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

               defaults: new { id=3 }

         );
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
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)
Helpers
1.   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)   Supplied
     b)   Current request
     c)   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
Areas
public 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 }
           );
       }
   }
Areas
AreaRegistration.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)

                                     MvcContrib
                             http://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/
Q&A


      www.emadashi.com
         @EmadAshi
Ad

More Related Content

What's hot (20)

React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
Remo Jansen
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jaydeep Kale
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
Sultan Ahmed
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
felixbillon
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in android
manjakannar
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
FITC
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
Christoffer Noring
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
Dinesh Sharma
 
Servlet Filters
Servlet FiltersServlet Filters
Servlet Filters
Wings Interactive
 
PHP MVC
PHP MVCPHP MVC
PHP MVC
Reggie Niccolo Santos
 
React for Beginners
React for BeginnersReact for Beginners
React for Beginners
Derek Willian Stavis
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
interface in c#
interface in c#interface in c#
interface in c#
Deepti Pillai
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
Remo Jansen
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
Sultan Ahmed
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
felixbillon
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in android
manjakannar
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
FITC
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
Dinesh Sharma
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 

Similar to ASP.NET Routing & MVC (20)

ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
Divya Sharma
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
Munish Gupta
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
Filip Janevski
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
Sagara Gunathunga
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
soelinn
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Pattern
maddinapudi
 
cake phptutorial
cake phptutorialcake phptutorial
cake phptutorial
ice27
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
Bozhidar Bozhanov
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
goodfriday
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
Pratchaya Suputsopon
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
Pushkar Chivate
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
Mark
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 
Node.js and Parse
Node.js and ParseNode.js and Parse
Node.js and Parse
Nicholas McClay
 
Resource and view
Resource and viewResource and view
Resource and view
Papp Laszlo
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
jonromero
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
Sagara Gunathunga
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
soelinn
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Pattern
maddinapudi
 
cake phptutorial
cake phptutorialcake phptutorial
cake phptutorial
ice27
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
goodfriday
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
Pushkar Chivate
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
Mark
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 
Resource and view
Resource and viewResource and view
Resource and view
Papp Laszlo
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
jonromero
 
Ad

More from Emad Alashi (12)

RBAC in Azure Kubernetes Service AKS
RBAC in Azure Kubernetes Service AKSRBAC in Azure Kubernetes Service AKS
RBAC in Azure Kubernetes Service AKS
Emad Alashi
 
Am I a Good Developer
Am I a Good DeveloperAm I a Good Developer
Am I a Good Developer
Emad Alashi
 
Basic Intro to WinDbg
Basic Intro to WinDbgBasic Intro to WinDbg
Basic Intro to WinDbg
Emad Alashi
 
Acquiring knowledge
Acquiring knowledgeAcquiring knowledge
Acquiring knowledge
Emad Alashi
 
Owin, Katana, and Helios
Owin, Katana, and HeliosOwin, Katana, and Helios
Owin, Katana, and Helios
Emad Alashi
 
OAuth in the new .NET world (OWIN)
OAuth in the new .NET world (OWIN)OAuth in the new .NET world (OWIN)
OAuth in the new .NET world (OWIN)
Emad Alashi
 
Software Life Cycle, Humans & Code
Software Life Cycle, Humans & CodeSoftware Life Cycle, Humans & Code
Software Life Cycle, Humans & Code
Emad Alashi
 
HTML5 & IE
HTML5 & IEHTML5 & IE
HTML5 & IE
Emad Alashi
 
ASP.NET MVC One Step Deeper
ASP.NET MVC One Step DeeperASP.NET MVC One Step Deeper
ASP.NET MVC One Step Deeper
Emad Alashi
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Emad Alashi
 
Communication Skills one To one
Communication Skills one To oneCommunication Skills one To one
Communication Skills one To one
Emad Alashi
 
Introduction To NHibernate
Introduction To NHibernateIntroduction To NHibernate
Introduction To NHibernate
Emad Alashi
 
RBAC in Azure Kubernetes Service AKS
RBAC in Azure Kubernetes Service AKSRBAC in Azure Kubernetes Service AKS
RBAC in Azure Kubernetes Service AKS
Emad Alashi
 
Am I a Good Developer
Am I a Good DeveloperAm I a Good Developer
Am I a Good Developer
Emad Alashi
 
Basic Intro to WinDbg
Basic Intro to WinDbgBasic Intro to WinDbg
Basic Intro to WinDbg
Emad Alashi
 
Acquiring knowledge
Acquiring knowledgeAcquiring knowledge
Acquiring knowledge
Emad Alashi
 
Owin, Katana, and Helios
Owin, Katana, and HeliosOwin, Katana, and Helios
Owin, Katana, and Helios
Emad Alashi
 
OAuth in the new .NET world (OWIN)
OAuth in the new .NET world (OWIN)OAuth in the new .NET world (OWIN)
OAuth in the new .NET world (OWIN)
Emad Alashi
 
Software Life Cycle, Humans & Code
Software Life Cycle, Humans & CodeSoftware Life Cycle, Humans & Code
Software Life Cycle, Humans & Code
Emad Alashi
 
ASP.NET MVC One Step Deeper
ASP.NET MVC One Step DeeperASP.NET MVC One Step Deeper
ASP.NET MVC One Step Deeper
Emad Alashi
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Emad Alashi
 
Communication Skills one To one
Communication Skills one To oneCommunication Skills one To one
Communication Skills one To one
Emad Alashi
 
Introduction To NHibernate
Introduction To NHibernateIntroduction To NHibernate
Introduction To NHibernate
Emad Alashi
 
Ad

Recently uploaded (20)

Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 

ASP.NET Routing & MVC

  • 2. URL Routing & MVC ALL YOUR URL ARE BELONG TO YOU!
  • 3. Agenda • Why understanding Routing is important • What is Routing? • How it works • How to test it • Best Some practices
  • 4. Why understanding Routing • The entry to your web app • HyperTextTransferProtol • Strongly relates to Binding • Never stay in doubt
  • 5. What is URL Routing
  • 6. History /store/products.aspx?key=value Store Page life cycle QueryString*“..”+ Products.aspx
  • 7. Handlers Store/products/apples • Parse • Extract variables OtherHttpHandler • Route to Handler URL MVCHttpHandler
  • 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. Priority We 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"} );
  • 11. Segmentation http://store.com/home/index First segment Second segment
  • 12. Static words “,controller- /,action-” “home/index” “anything/willdo” ============================= “abc,controller- / ,action-” “abchome / whatever” ================== “abc,controller- / ,action-” “home / whatever”
  • 13. RouteData.Values “,controller}/{action-/,id-” “product/index/3” Variable value controller Product action Index id 3
  • 14. Defaults Or 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. 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. 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. 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)
  • 19. Notes (Incoming) • Reserved custom variables: “controller, action, area” • routes.RouteExistingFiles = true; • routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); • Last segment includes the QueryString
  • 20. How Routing works (Outgoing)
  • 21. Helpers 1. 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. Rules 1. All variables should have values: “,controller-/,action-/,id-” a) Supplied b) Current request c) Default values 2. Should not dis-agree with default-only variables: routes.MapRoute("MyRoute", "{controller}/{action}", new { myVar = "true" }); 3. Satisfy constraints
  • 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. Areas
  • 25. Areas public 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 } ); } }
  • 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 variables as expected.
  • 29. Unit-Testing Routes (Incoming) • Incoming: • HttpRequestBase • HttpContextBase • HttpResponseBase • Outcoing: • + • UrlHelper
  • 31. Unit-Testing Routes (Incoming) MvcContrib http://mvccontrib.codeplex.com/ "~/Products/View/44/offer".ShouldMapTo<ProductsController>(action => action.View(44, “offer"));
  • 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. ASP.NET It’s all open source! http://aspnetwebstack.codeplex.com/
  • 34. Q&A www.emadashi.com @EmadAshi

Editor's Notes

  • #3: How many dealt with ASP.NET and HttpHandler
  • #7: 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”)
  • #8: 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
  • #9: So we could be rigid, or dynamicBut how can we make programmers more interesting and harder? :P
  • #10: At the startup of the web app
  • #11: It’s hard to put it in steps since it’s little bit complex and wined together, but we will try
  • #16: “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?)
  • #18: Specific values for controllers that might share a URL patternHttp Method has nothing to do with the “post” and “get” action filters
  • #19: Inspired by RouteDebugger created by Phil Haack
  • #20: Last segment includes the query string, but it’s up to the IHttpHandler how to handle it
  • #22: 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
  • #24: 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:
  • #26: Don’t change namespace of controller in an AreaDo use namespace priority for the general controller
  • #27: Don’t change the order of Area registration to be after Routing
  • #29: Because it’s the key for the MVCHttpHandlerBy: checking the orderChecking the static stringsChecking constraints if we have them
  • #30: Before, it was hard to test Routes, now they provided HttpContextBase
  • #31: Before, it was hard to test Routes, now they provided HttpContextBase
  • #32: “offer” might be date as wellI am not totally enthusiast since this is not testing Routing only, it intervenes of how binding works
  • #33: 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
  • #34: For me, sometimes Reflector is easier to navigate