Month: February 2016

ASP.NET MVC Routers common questions

I’m doing this article as a self remainder of how to declare routers in ASP.NET MVC I will try to answer the most common questions about ASP.NET MVC Routers that I was able to find on internet. Hopefully this might help you as well. Routers

When you create a MVC application with Visual Studio, and you go to the RouteConfig.cs file this is the default code generate by the template:

                name: "Default",
                defaults: new { controller = "Home", 
                                action = "Index", 
                                id = UrlParameter.Optional },

Most common questions about routers:

“Why do we use route.IgnoreRoute?”
This will tells the routing engine to ignore any requests that match the provided pattern “{resource}.axd/{*pathInfo}”. In this case to ignore any requests to axd resources.

“Why the parameters in {} ?”
The {} indicates that the delimited string is a variable, it can anything. In the ignore route this is used so that any .axd requests are matched.

Why map MapRoute has First parameter “Default”
The first parameter is the route name. This can be used when referring to routes by name. It can be null

  "Default", //Default Route

  "Feedback", // Custom Route name
   new { controller = "Home", action = "Feedback" }

//Then you can call it like this:

What is the Second Parameter-“{controller}/{action}/{id}” for?
This is the pattern that is matched. In this case it is setting up the default route which is a url formed by the controller name, action name and an optional id. The url would call the Bar method on the Foo controller. Changing the url to would pass a parameter with the identifier id and value 1.

What is the third parameter?
The third parameter supplies defaults. In the case of the default route the default controller name is Home and the default action is Index. The outcome of this is that a request to would call the Index method on the Home controller. The id part of the route is specified as being optional with UrlParameter.Optional.

What is the fourth parameter?
The fourth parameter is for constraints, you can use regular expressions, in this example in particular this expression “\d+” match strings that are sequences of one or more digits (0-9).

How to create a custom Routers Constraint?
For this example we are going to create a Guid constraing, we have to create a class that inherit from IRouteConstraint and implement it:
routers implement interface
This is the code:

public class GuidConstraint : IRouteConstraint {

                  RouteValueDictionary values, RouteDirection routeDirection)
    if (values.ContainsKey(parameterName))
        string stringValue = values[parameterName] as string;
        if (!string.IsNullOrEmpty(stringValue))
            Guid guidValue;
            return Guid.TryParse(stringValue, out guidValue) && (guidValue != Guid.Empty);
    return false;

You can use it in the route like this:

routes.MapRoute("doubleGuid", "{controller}/{action}/{guid1}", 
                 new { controller = "YourController", action = "YourAction" }, 
                 new { guid1 = new GuidConstraint() });

Why we use new?
The new keyword is creating/instanciating an object using the object initializer syntax that was introduced in version 3 of the .Net framework.

Difference between “MapHttpRoute” and “MapRoute”?
ultimately both operate on the same underlying ASP.NET route table, the difference is that MapRoute is used for when the application is hosted in ASP.NET. MapHttpRoute is used for Web Apis for when hosting outside of ASP.NET, Web API wouldn’t have to rely on System.Web.
Web API is not sitting on top of MVC, Web Forms, or, for that matter ASP.NET at all. It can be hosted within web context (ASP.NET) but can also be self hosted in a Console app, WPF, etc.

The major advantage of using routing is that it creates a convention for your Urls. If you created a new controller called Account and action methods called Index and Review then the methods would be available at /Account and Account/Review respectively.

Other resources: