A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. A handler can also be a class that processes the request, such as a controller in an MVC application. To define a route, you create an instance of the Route class by specifying the URL pattern, the handler, and optionally a name for the route.

All the configured routes of an application stored in RouteTable and will be used by Routing engine to determine appropriate handler class or file for an incoming request.

The ASP.NET MVC framework and ASP.NET Dynamic Data extend routing to provide features that are used only in MVC applications and in Dynamic Data applications.

Configure Route:

Every MVC application must configure (register) at least one route, which is configured by MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig.cs under App_Start folder.

Route is configured using the MapRoute() extension method of RouteCollection, where name is "Default", url pattern is "{controller}/{action}/{id}" and defaults parameter for controller, action method and id parameter. Defaults specifies which controller, action method or value of id parameter should be used if they do not exist in the incoming request URL.

URL Patterns:

A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL which are delimited by the slash (/) character. The URL pattern is considered only after domain name part in the URL. For example, the URL pattern "{controller}/{action}/{id}" would look like localhost:4657/{controller}/{action}/{id}. Anything after "localhost:4657/" would be considered as controller name. The same way, anything after controller name would be considered as action name and then value of id parameter. If the URL doesn't contain anything after domain name then the default controller and action method will handle the request.

Route Constraints:

You can also apply restrictions on the value of parameter by configuring route constraints. For example, the following route applies a restriction on id parameter that the value of an id must be numeric.

We can define such a constraint as:

If a URL matches a route but the placeholder does not satisfy the constraint the route is not considered a valid match and the routing engine continues searching for the matching route. So using the constraints we can specify the validations on the placeholder values which would otherwise throw exception.

0 Comments1

Sorry, No more post.

Your Comment

Login To Comment

discard

By posting your Comment, you agree to the privacy policy and terms of service.