Friday, June 4, 2021

MVC Conventional or Traditional Routing Concepts

Topics Overview

  • What is HTTP?
  • What are HTTP verbs?
  • What is URL?
  • What is Route?
  • What is Route Table?
  • What is Routing?
  • What is RouteCollection?
  • What is MapRoute?
  • How Routing works?

What is HTTP?

HTTP(Hypertext Transfer Protocol) is a protocol or set of rules which is followed between client and server during data(hypertext) transfer over the network. The words server and client refers either to a computer or to a computer program depending upon the context. Originally it was protocol to transfer hypertext over network but later with advancement of web technologies, hypermedia transfer became possible. Hypermedia can be text, audio, video, graphic etc.

According to MDN, Hypertext Transfer Protocol (HTTP) is an application-layer protocol for transmitting hypermedia documents, such as HTML. It was designed for communication between web browsers and web servers, but it can also be used for other purposes.
  • HTTP follows a classical client-server model, with a client opening a connection to make a request, then waiting until it receives a response. 
  • HTTP is a stateless protocol, meaning that the server does not keep any data (state) between two requests. Though often based on a TCP/IP layer, it can be used on any reliable transport layer, that is, a protocol that doesn't lose messages silently like UDP does. 

What are HTTP verbs?

The following methods or actions or verbs are used during data transfer between client and server. Mostly GET and POST verbs are used in MVC projects while other verbs such as PUT, DELETE, PATCH, etc. are used in Web API projects
  • HTTP GET verb is used to get data from the database via database server and is transferred to client browser. When the client software requests for data, it specifies the nature of HTTP verb in its HEADER.
  • HTTP POST verb is used to create new resource in database. For example, to add new record in a table of the database. Create action methods in MVC.
  • HTTP PUT verb is used to update existing resource in database. For example, to update a record in a table of the database.
  • HTTP PATCH verb is used to partially update existing resource in database. For example, to update a field of record in a table of the database.
  • HTTP DELETE verb is used to delete existing resource in database. For example, to delete a record in a table of the database. Delete action methods in MVC.

How is HTTP verb get or set? 

In HTML Form, the action and method attributes are used. The method attribute of form tag is used to set the HTTP verb. For example 
<form action ="" method="POST"> </form>
 
In MVC, [HttpGet] and [HttpPost] attributes are used to decorate the action methods. We will see it later in attribute routing.

What is URL?

URL is acronym of Uniform Resource Locator. The URL is address of a computer resource such as text file, image file, audio, video or program file etc. on the Internet or local drive. Just as a person has address to locate him/her, URL is address to locate a computer resource. 

To access a computer resource from a network or local drive, different protocols i.e. set of rules are required. Examples are http, ftp, file, mailto, gopher, news etc. Following a protocol a particular resource is accessed from 

The URL contains at least three components in order. They are protocol type, domain name and then target resource path. No whitespace is given a URL. 
EXAMPLE1
For example http://appliedk.blogspot.com/2021/02/list-of-contents.html In this URL, http is protocol which is followed by colon and then forward slashes. Then domain name appliedk.blogspot.com is given which is separated from file full path 2021/02/list-of-contents.html by forward slash.

The type of protocol used to access the resource can be http for a web page, ftp for an FTP site or file for local drive etc. The domain name or IP address of the server where the resource resides; and, finally third component is optional pathname to the target resource. If we ignore the third component, we reach to the server where the resource is located.

EXAMPLE2
Another example, the URL http://appliedk.blogspot.com/2021/05/c-namespace.html is an instruction about the target resource. It instructs the browser to use the HTTP protocol (HTTP means that the resource web page can be accessed through network following certain rules), and then go to the appliedk.blogspot.com web server, and then access the c-namespace.html file in folder subfolder file hierarchy 2020/05.

What is Routing?

When URL is typed in the address bar of the browser, the resource is fetched from the target path. But the question is how the route of the destination resource is decided? The entire mechanism to access the resource from the target is called routing. In this process, the URL passed is address bar is matched with the Routing URL pattern defined in RouteConfig.cs file in ASP.NET MVC framework. We will see it ahead.

MVC Projects and URL Pattern
In .NET MVC projects, routing is defined in RouteConfig.cs file. This is a class file which has RegisterRoutes(RouteCollection routes) method. This method accepts an input argument of RouteCollection class type. The RouteCollection class has MapRoute method which has three named parameters. They are name, url, and defaults. This method is used to map a route i.e. selecting a controller and then one of its action methods. We have to learn about these classes and methods to understand routing in .NET MVC

Traditional Routing in MVC

Conventional or traditional routing is used in earlier versions of MVC before MVC5. The conventional routing can be used in MVC version 5 also. The conventional or traditional routing is defined in RouteConfig.cs file. When MVC application starts, the RegisterRoute() method is called in the global.asax file as shown below.

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //When App starts all Routes of RouteTable are registered
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }

Note that when the application starts, all the routes of routing table are registered. But route must be configured in the RouteConfig.cs file.

How to configure the RouteConfig.cs file

We will learn how the RouteConfig.cs file can be configured for conventional or traditional routing. The RouteConfig.cs file exists in App_Start folder.

In MVC, a route is all about calling an action method of a controller class. Which action method of which controller will be invoked decides a route in MVC. 

Technically, an MVC Route is a pattern with four parameters: name, url, defaults and constraints; some of these parameters are optional. MapRoute method is passed these parameters. MapRoute method is member of RouteCollection class. The MapRoute method returns a reference to the mapped Route class object. We will see it ahead. But now we have to know the following facts:
  • Each MapRoute method has a unique string name parameter to identify the route among the RouteCollection.
  • Each MapRoute method has a unique string url parameter which specifies the pattern of the URL passed in the address bar of the browser.
  • Each MapRoute method has an object defaults parameter. This object is instantiated with three parameters which are initialized for controller, action and id.
Depending upon a route pattern defined in the MapRoute method of RouteConfig.cs file, an action method of a controller class is called.

Merits of MVC URL

The URL in MVC is SEO friendly and very logical as per the business. Following are examples of MVC URL. They follow the syntax like domain-name/controller-name/action-name/id
  • domain.com/Employee
  • domain.com/Employee/Salary
  • domain.com/Employee/Salary/2

MapRoute() method

Conventional routing is all about writing the parameters of the MapRoute() method in the RouteConfig.cs file. We have to learn the technique of how to specify each parameter of the MapRoute() method. Each time we decide to add a new route, we write a separate MapRoute() method. Among these several methods, which method will be called is decided as per the url pattern in the browser address bar specified. 

All three parameters of MapRoute() method are mandatory. Further, name parameter of each MapRoute() method is unique and the given the url pattern to url parameter, the defaults parameter is used to decide which controller and action method will be called. 

In the url parameter, if {} braces are used then it works as placeholder to hold controller, action and id, otherwise the literal meaning is understood. For example, url: "{controller}/{action}/{id}" Here controller, action and id stands for controller, action and id passed in the address bar of browser. For example, domain/Student/Address/1 implies to get the Address action method of the Student controller and Student id is 1. 

To allow any arbitrary id, we will write the url pattern as follows: domain/Student/Address/{id} In this scenario the Address(int id) action method will be invoked but the id is not hard-coded. The user can pass any url in the address bar such as domain/Student/Address/1 or domain/Student/Address/2 or domain/Student/Address/3 etc. But what if we want a fixed id value(say id=2) , no matter what id value is passed by the user in the address bar? To achieve it, we write the following url pattern. 
url: domain/Student/Address/{id}
defaults: new {controller= "Student", action="Address" , id = 2}

How many overloaded methods exist for MapRoute() method?
There are 6 overloads of MapRoute() method. We have the following cases.
  1. routes.MapRoute(string name , string url)
  2. routes.MapRoute(string name , string url, object defaults)
  3. routes.MapRoute(string name , string url, string[] namespaces)
  4. routes.MapRoute(string name , string url, object defaults, object constraints)
  5. routes.MapRoute(string name , string url, object defaults, string[] namespaces)
  6. routes.MapRoute(string name , string url, object defaults, object constraints, string[] namespaces)

No comments:

Post a Comment

Hot Topics