Home > ASP.NET MVC, Uncategorized > ASP.NET MVC Routing

ASP.NET MVC Routing

Before asp.net mvc in asp.net all the request was assumed to point to some physical file like
Request Url: http://mvctest.com/default.aspx
Corresponding File: e:\root \default.aspx

This concept was good for asp.net web form. But for asp.net mvc where request will be processed by controller and action the file based concept will not work. To handle routing asp.net introduces new routing system.

The Routing System
The routing system has two functions:
1. Examine an incoming URL and figure out for which controller and action
the request is intended.
2. Generate outgoing URLs. These are the URLs that appear in the HTML rendered
from our views so that a specific action will be invoked when the user clicks the
link (at which point, it has become an incoming URL again).
In an asp.net mvc project routes are defined in Global.asax file. If you open this file in Visual Studio, you will see that routes take up quite a lot of this (admittedly short) file.
Here is a sample global.ajax file.

using System.Web.Mvc;
using System.Web.Routing;
namespace UrlsAndRoutes {

public class MvcTestApplication : System.Web.HttpApplication {

protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes) {
//routes are defined here...
}

public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new HandleErrorAttribute());
}
}
}

Here the application_start event will be called on application start up (when the application will get the first request). And then RegisterRoutes method will register the routes as defined.

Routing Patterns
The route should be defined by some url patterns. We don’t need to define each and every route in the route registration instead we need to define some patterns as required.

Let’s start with an example with url http://mvctest.com/home/index
The url will point to action index of controller home.
The above url can be broken into segments excluding sitename and querystring.
So,
Home —- First Segment
Index —– Second Segment

Where it is apparent that first segment is the controller and second segment is the action. But we need to express this relationship in a way that the routing system can understand.
Here is the url pattern that does it

{controller}/{action}

Two key behaviors of URL patterns:
• URL patterns are conservative, and will match only URLs that have the same
number of segments as the pattern. You can see this in the fourth and fifth
examples in the table.
• URL patterns are liberal. If a URL does have the correct number of segments, the
pattern will extract the value for the segment variable, whatever it might be.

Creating and Registering a sample route
If we get some url pattern then we need to define it in the RegisterRoutesmethods.

Here is the example how can you define route:

public static void RegisterRoutes(RouteCollection routes) {
Route myRoute = new Route("{controller}/{action}", new MvcRouteHandler());
routes.Add("MyRoute", myRoute);
}

OR

public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}");
}

The second one is more convenient. mainly because we don’t need to create an instance of the
MvcRouteHandler class. The MapRoute method is solely for use with MVC applications. ASP.NET Web
Forms applications can use the MapPageRoute method, also defined in the RouteCollection class.

Default Values
As, URL patterns are conservative, in that they will match only URLs with the specified number of segments. We also said that this was the default behavior. One way to change this behavior is to use default values. A default value is applied when the URL doesn’t contain a segment that can be matched to the value.

For example:

public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}",
new { controller = "Home", action = "Index" });
}

Here, if we not provide segment one and two in the url (e.g. : http://mvctest.com) then the controller and action will get the default values.
That is controller = “Home”, action=”Index”.
So the request http://mvctest.com will be treated as http://mvctest.com/home/index

Using Static URL Segments
Not all of the segments in a URL pattern need to be variables. You can also create patterns that have
static segments. Suppose we want to match a URL like this to support URLs that are prefixed with
Public:
http://mvctest.com/Public/Home/Index

We can do this by:

public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("publicRoute", "Public/{controller}/{action}",
new { controller = "Home", action = "Index" });
}

Defining Custom Segment Variables
We are not limited to just the controller and action variables. We can also define our own variables, as

public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "DefaultId" });
}

Then we can use the custom veriable in the action parameter which will be bound automatically.
So for request http://mvctest.com/home/get/2
With action

public ViewResult get(string id) {
return View();
}

Here id will be 2.

Defining Variable-Length Routes
Another way of changing the default conservatism of URL patterns is to accept a variable number of URL
segments. This allows you to route URLs of arbitrary lengths in a single route. You define support for
variable segments by designating one of the segment variables as a catchall, done by prefixing it with an
asterisk (*)

public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

So for url like this http://mvctest.com/Customer/List/All/Delete will also pass the pattern.

Advertisements
Categories: ASP.NET MVC, Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: