Routing in Asp.Net MVC

Overview

This lesson is all about Routing in Asp.Net MVC. Contents of lesson.

What is Routing ?Benefits of Routing in MVC
Routing in Asp.Net MVC
Create Custom Routes

Introduction

Uniform Resource Locator (URL) is used to identify the unique handler to process incoming request. URL Routing in MVC is a fundamental concept to understand. It defines URL pattern in your MVC application and finds proper handler to process the incoming request.

Benefits of Routing in MVC

If you are familiar with Asp.Net Web Form, URLs in these applications will be like this,

http://<domain>/Books/Order.aspx

URL is mapping to a physical file Order.aspx inside Books folder. If we want to pass additional data, we will use query string in URLs like

http://<domain>/Books/Order.aspx?id=1309&stage=2

These URLs will be meaningful and easy to remember for developers but  it won’t be the case with users, they don’t have any idea about aspx extension, table id and stage query string. If you add more data through query string it would be a mess for users.

Here comes the important of Routing in Asp.Net Mvc. URLs in Mvc applications are

  • User friendly and meaning full.
  • SEO friendly.

Suppose you are going to create an application for library management in Asp.Net MVC. Then you can have URLs to

Show books from an author
http://<domain>/BooksByAuthor/<authorname>
eg : http://<domain>/BooksByAuthor/Shakespeare

List books under a category
http://<domain>/BooksByCategory/<cateogory> 
eg : http://<domain>/BooksByCategory/Drama

These types of URLs are friendly to both user and developer. User can play around the URL to get what they want.

MVC URLs are SEO friendly : SEO (Search Engine Optimization) is the process of applying some best practices to get more traffic through search engines like Google, Bing etc. Short and meaning URLs like MVC URL is good for SEO.

Routes

Route is a URL pattern that is mapped to a request handler.

In MVC, Handler is our MVC Controller.Mvc Controller in Solution Explorer

We will understand Controller and Action Method in detail from upcoming chapters, But in order to understand routing you need to have the basic concept of Controller and Action Method.

In solution explorer, All of our MVC Controller are saved inside Controller Folder. Controller name must end with ‘Controller’ like HomeController, AccountController etc. It is nothing but a Class that is inherited from Controller Class( which is inherited from BaseController Class) like below,

Action Methods are the functions inside these Controller Class. In most of the case it will return html string, JSON etc.

URL Patterns

URL pattern is a combination of literal values and variable placeholders.

Variable placeholder will be replaced by controller name,action method etc in actual URL. Literal values are the strings, it will be there in actual URL as it is.

Structure of URL Pattern

Mvc Url Pattern

Literals and placeholders are delimited by a slash(/). Placeholders are enclosed inside curly braces – {}. Portion between two adjacent slash( / ) delimiter is called segments in URL pattern.

Routing in Asp.Net MVC

Solution Explorer Showing Files Related to RoutingNow let’s check how routing is implemented in Asp.Net Mvc. In Our Mvc Application there are two files associated with routing.

  • RouteConfig.cs
  • Global.asax.cs

Inside RoutConfig.cs, there is a function RegisterRoutes to add all routes in the application. While starting the application Global.asax.cs file will invoke the function  RegisterRoutes to register the routes.

Now let’s check RouteConfig.cs.

This is the default routing in our MVC application. MapRoute function is used to add new routes into the application.

name parameter is used to name the route and it must be unique.

Then we have url to specify the URL pattern, {controller} and {action} are two reserved placeholder in MVC routing.{id} is the last placeholder.

finally we will specify default values for these placeholders. Home is the default controller and Index is the default Action Method, id is marked as optional parameter.

Routing in Asp.Net Mvc Means picking the right Controller and Action Method.

Suppose you make a request with http://<domain>/Home/Index URL. It will find the default route as matching for this URL. So it will make following assumptions,

Home is a controllerIndex is an Action Method. So it will look for Index Action Method inside HomeController . if it exist, it will handle the request, other wise routing module will raise 404 ( File Not Found) Error.

Now if you make a request without controller or action method it will look for default values.

Routing Examples

Consider following URLs and routing

http://<domain>/
Home is the Controller and Index is the Action Method (from default).

http://<domain>/Account/
Account is the controller. Index is the Action Method (from default).

http://<domain>/Home/Index/2
Home controller – Index Action. id is 2.

When a request is made. URL is parsed into segments, placeholder and literal values. Then checks for matching URL pattern in the application. If there is any matching pattern, then based on the pattern corresponding controller and action method can be found. additional parameters will be passed as function parameter to the Action Method.

In RegisterRoutes function, you can see a line like this

It tells the route module to ignore URLs of this pattern, because MVC framework knows better to handle these types of URL request.

Custom Routes in MVC

When your application become big and complex, you may need to add routes into your application.

Suppose I want to generate report showing monthly demand for an author. We need an URL pattern like this,

http:///AuthorMonthlyReport/2017/Aug/Stephen

then it will show the demand of Stephen’s Books for the month August-2017. So in that case, I will add the route like this.

So the URL pattern routes the request to Author Controller. The controller will looks like this.

If you have more than one route in your application. Then more specific routes should be placed in the top to bottom. Because URL patterns are matched from top. first matching Pattern will be used to route the request.

 

Previous Lesson

Comments are closed