SlideShare uma empresa Scribd logo
1 de 34
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

Mais conteúdo relacionado

Mais procurados

Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Edureka!
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular ComponentsSquash Apps Pvt Ltd
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].pptGaganvirKaur
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Edureka!
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 

Mais procurados (20)

Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
PythonOOP
PythonOOPPythonOOP
PythonOOP
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
Php basics
Php basicsPhp basics
Php basics
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].ppt
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
C++ string
C++ stringC++ string
C++ string
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Flask
FlaskFlask
Flask
 
Python 2 vs. Python 3
Python 2 vs. Python 3Python 2 vs. Python 3
Python 2 vs. Python 3
 

Semelhante a ASP.NET Routing & MVC

Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda 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-rsSagara Gunathunga
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4soelinn
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael 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 Patternmaddinapudi
 
cake phptutorial
cake phptutorialcake phptutorial
cake phptutorialice27
 
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 Patterngoodfriday
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015Pushkar Chivate
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js FundamentalsMark
 
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 jsFrancois Zaninotto
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Resource and view
Resource and viewResource and view
Resource and viewPapp Laszlo
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2pyjonromero
 

Semelhante a ASP.NET Routing & MVC (20)

ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
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
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Pattern
 
cake phptutorial
cake phptutorialcake phptutorial
cake phptutorial
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 
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
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
 
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
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Node.js and Parse
Node.js and ParseNode.js and Parse
Node.js and Parse
 
Resource and view
Resource and viewResource and view
Resource and view
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
 

Mais de Emad Alashi

RBAC in Azure Kubernetes Service AKS
RBAC in Azure Kubernetes Service AKSRBAC in Azure Kubernetes Service AKS
RBAC in Azure Kubernetes Service AKSEmad Alashi
 
Am I a Good Developer
Am I a Good DeveloperAm I a Good Developer
Am I a Good DeveloperEmad Alashi
 
Basic Intro to WinDbg
Basic Intro to WinDbgBasic Intro to WinDbg
Basic Intro to WinDbgEmad Alashi
 
Acquiring knowledge
Acquiring knowledgeAcquiring knowledge
Acquiring knowledgeEmad Alashi
 
Owin, Katana, and Helios
Owin, Katana, and HeliosOwin, Katana, and Helios
Owin, Katana, and HeliosEmad 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 & CodeEmad Alashi
 
ASP.NET MVC One Step Deeper
ASP.NET MVC One Step DeeperASP.NET MVC One Step Deeper
ASP.NET MVC One Step DeeperEmad Alashi
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCEmad Alashi
 
Communication Skills one To one
Communication Skills one To oneCommunication Skills one To one
Communication Skills one To oneEmad Alashi
 
Introduction To NHibernate
Introduction To NHibernateIntroduction To NHibernate
Introduction To NHibernateEmad Alashi
 

Mais de 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
 
Am I a Good Developer
Am I a Good DeveloperAm I a Good Developer
Am I a Good Developer
 
Basic Intro to WinDbg
Basic Intro to WinDbgBasic Intro to WinDbg
Basic Intro to WinDbg
 
Acquiring knowledge
Acquiring knowledgeAcquiring knowledge
Acquiring knowledge
 
Owin, Katana, and Helios
Owin, Katana, and HeliosOwin, Katana, and Helios
Owin, Katana, and Helios
 
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)
 
Software Life Cycle, Humans & Code
Software Life Cycle, Humans & CodeSoftware Life Cycle, Humans & Code
Software Life Cycle, Humans & Code
 
HTML5 & IE
HTML5 & IEHTML5 & IE
HTML5 & IE
 
ASP.NET MVC One Step Deeper
ASP.NET MVC One Step DeeperASP.NET MVC One Step Deeper
ASP.NET MVC One Step Deeper
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Communication Skills one To one
Communication Skills one To oneCommunication Skills one To one
Communication Skills one To one
 
Introduction To NHibernate
Introduction To NHibernateIntroduction To NHibernate
Introduction To NHibernate
 

Último

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 

Último (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 

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

Notas do Editor

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