ASP.NET MVC Routing
ASP.NET MVC routing is
a pattern matching system that is responsible for mapping incoming browser
requests to specified MVC controller actions. When the ASP.NET MVC application
launches then the application registers one or more patterns with the
framework's route table to tell the routing engine what to do with any requests
that matches those patterns. When the routing engine receives a request at
runtime, it matches that request's URL against the URL patterns registered with
it and gives the response according to a pattern match.
Routing pattern is as follows
A URL is requested
from a browser, the URL is parsed (that is, break into controller and action),
the parsed URL is compared to registered route pattern in the framework’s route
table, if a route is found, its process and send response to the browser with
the required response, otherwise, the HTTP 404 error is send to the browser.
Route Properties
ASP.NET MVC routes are
responsible for determining which controller method to execute for a given URL.
A URL consists of the following properties:
- Route Name: A route is a URL pattern that is mapped to a handler. A
handler can be a controller in the MVC application that processes the
request. A route name may be used as a specific reference to a given
route.
- URL Pattern: A URL pattern can contain literal values and variable
placeholders (also known as URL parameters). The literals and placeholders
are located in segments of the URL that are delimited by the slash (/)
character.
When a request is made, the URL is parsed into segments and placeholders, and the variable values are provided to the request handler. This process is similar to the way the data in query strings is parsed and passed to the request handler. In both cases variable information is included in the URL and passed to the handler in the form of key-value pairs. For query strings both the keys and the values are in the URL. For routes, the keys are the placeholder names defined in the URL pattern, and only the values are in the URL.
- Defaults: When you define a route, you can assign a default value
for a parameter. The defaults is an object that contains default route
values.
- Constraints: A set of constraints to apply against the URL pattern
to more narrowly define the URL that it matches.
The Default Route
The default ASP.NET MVC
project templates add a generic route that uses the following URL convention to
break the URL for a given request into three named segments.
url:
"{controller}/{action}/{id}"
This route pattern is
registered via call to the MapRoute() extension method of RouteCollection. As
shown in the below figure.
When
an MVC application first starts, the Application_Start() method is called. This
method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method
creates the route table.
The default route table contains a single route (named Default). The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id.
Imagine that you enter the following URL into your web browser's address bar:
/Guests/Index/3
The Default route maps this URL to the following parameters:
·
controller = Home
·
action = Index
·
id = 3
When you request the URL /Home/Index/3, the following code is executed:
GuestsController.Index(3)
The Default route includes defaults for all three parameters. If you don't supply a controller, then the controller parameter defaults to the value Guests. If you don't supply an action, the action parameter defaults to the value Index. Finally, if you don't supply an id, the id parameter defaults to an empty string.
Let's look at a few examples of how the Default route maps URLs to controller actions. Imagine that you enter the following URL into your browser address bar:
/Guests
Because of the Default route parameter defaults, entering this URL will cause the Index() method of the GuestsController class as in Listing below to be called.
// GET: Guests
public ActionResult Index()
{
return View(db.Guests.ToList());
}
ASP.NET MVC Routing with an Example
When the application
starts up, ASP.NET MVC discovers all of the application's controllers by
searching through the available assemblies for a class that implements the
System.Web.Mvc.IController interface or derived from a class that implements
this interface and whose class names end with the suffix Controller. When the
routing framework uses this list to determine which controller it has access
to, it removes the Controller suffix from the entire controller class names.
In our previous
article, WebApp Tutorial with ASP.NET MVC using Model First Approach, we implemented Create, Read, Update and
Delete operations on a Guest entity. So we will use this example to understand
URL routing. Our default route is the same as shown below for CRUD applications
also.
URL
|
Controller
|
Action
|
Id
|
http://localhost:44302/
|
GuestsController
|
Index
|
|
http://localhost:44302/Guests/
|
GuestsController
|
Index
|
|
http://localhost:44302/Guests/Create
|
GuestsController
|
Create
|
|
http://localhost:44302/Guests/Edit/1
|
GuestsController
|
Edit
|
1
|
The last request's URL
(http://localhost:44302/Guests/Edit/1) in above table is a perfect match to the
registered default URL pattern because it satisfies every segment of the route
pattern, but when we don't provide a complete request's URL then the routing
engine automatically calls the controller and action method as per the default
route pattern.
Multiple Routes
You can also configure a custom route
using MapRoute extension method. You need to provide at least two parameters in
MapRoute, route name and url pattern. The Defaults parameter is optional.
You can register multiple custom routes with different names. Consider the following example where we register "Guests" route.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Guests",
url: "Guests/{id}",
defaults: new { controller = "Guests", action = "Index"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Register Routes
Now, after configuring
all the routes in RouteConfig class, you need to register it in the
Application_Start() event in the Global.asax. So that it includes all your
routes into RouteTable.
Route Registration
using System.Web.Routing;
namespace GuestInfoTutorial
{
public class MvcApplication :
System.Web.HttpApplication
{
protected void
Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
Summary
We have examined the
default route table that we get with a new ASP.NET MVC application. We also
learned how the default route maps URLs to controller actions
We should be noted
that controller and action values in the route are not case-sensitive. URL
route patterns are relative to the application root, so they don't need to
start with a forward slash (/) or virtual path designator (~/).
Comments
Post a Comment