Today, I am going to demonstrate how to create custom routing in Asp.Net MVC application. I hope you all know the routing concept; in short routing is used to map the incoming request to particular MVC controller action. It also customizes your url which looks neat and clean.

But today, I will not explain the routing concept, like what is routing in detail, how it work, how we can create etc. Actually I will try to explain the Custom Routing concept.  When you request for Asp.Net MVC page then it passes through the routing architecture. The default routing algorithm is like {controller}/ {action}/ {id}. But sometime we need to create our custom route which full feel our requirement.

When you create a Asp.Net MVC project than it auto create a default route inside the RouteConfig.cs which is located in App_Start folder.

Default Route
public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
Note: you can put this RegisterRoutes Method directly inside the Global.asax.cs file.

 

This RouteConfig is registered on the time of application start inside the Global.asax.cs

protected void Application_Start()
{
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
}

 

Custom Routing

You can develop an Asp.Net MVC application without use of Custom Routing but sometimes, there is a requirement to change the url in such a way that is not possible to create using simple routing. So, in that scenario we use the Custom Routing.

I will give you two examples where using routing you will not able to achieve the task but you can achieve it using Custom Routing.

Example I

Now, we can take a simple example for custom routing. Find the below url, can It possible by routing only.

www.domain.com/articles/csharp/mytesturl

Here you can see, after my domain name url is something like that “/articles/categoryname/urlofarticles”. So, how can we achieve this? Here you need to use custom routing.

You need to add a new route inside the RouteConfig.cs

routes.MapRoute("ArticlesPost", "articles/{category}/{url}",
                          new { controller = "Article", action = "ViewArticle" },
                          new { category = @"\S+", url = @"\S+" });

So, a question arises here, how to use it with link or something else. So, you can use this custom route by following way.

@Html.RouteLink(Model.PostTitle, " ArticlesPost ", new { category = Model.postCategory.Category, url = Model.PostUrl }, new { @class = "title" })

Here if pass the Model.postCategory.Category=”csharp” and Model.PostUrl=”mytesturl” than it will generate the url like below.

www.mydomain.com/articles/csharp/mytesturl

 

Example II

Now, we can take one more example to understand the custom routing. Find the below url, can it possible by routing only.

www.domain.com/articles/16-09-2015

Here you can see, after my domain name url is something like that “/articles/dateofarticle”. So, how can we achieve this? Here you also need to use custom routing.

You need to add a new route inside the RouteConfig.cs. 

routes.MapRoute("ArticlesPostByDate", "articles/{postdate}",
                          new { controller = "Article", action = "ArticleByDate" },
                          new { postdate = @"\d{2}-d{2}-d{4}" });

So, how can use it

@Html.RouteLink(Model.PostDate, "ArticlesPostByDate", new { postdate = Model.PostDate }, new { @class = "title" })

Here if pass the Model.PostDate =”16-09-2015” than it will generate the url like below.

www.domain.com/articles/16-09-2015

Regular Expression Constraints

Sometime you need to prevent the invalid request to route. So, you can use regular expression constraints to prevent the wrong or invalid request. Regular expression constraints are used to check pattern like text, integer value, date, time, currency etc.

 

Conclusion:

So, Today we learned how to create custom routing in Asp.Net MVC with examples.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks