Click here to Skip to main content
15,880,796 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET MVC Dynamic Routing

Rate me:
Please Sign up or sign in to vote.
4.29/5 (6 votes)
1 Oct 2014CPOL3 min read 53.2K   12   4
Learn how to route variable URL patterns to fixed Controller/Action

Introduction

In this tip, we would learn how to customize the ASP.NET MVC routing pattern and route variable URL paths to a controller and action of our choice.

Using the Code

To use the code, create a sample MVC project using basic ASP.NET MVC template. It gives you default views like index, login, etc.

Why

Currently, I’m building a Web based SaaS product and I had a requirement which I believe is quite common. I wanted my customers to access the site as www.youdomain.com/c1, www.yourdomain.com/c2, etc. with c1, c2… being the customer names. This would help me display a customized Login page for each customer as well as I would know which customer the user belongs to.

With ASP.NET MVC, I had 2 problems:

  1. Default route handles controller/actions whereas I as per my requirement had only controller to handle.
  2. I could not have a controller each for a customer and change code every time a new customer is added. This was not at all feasible.

I tried searching the net and could only find variation of default routing which would not solve my problem.There was another option where I could control the routing logic by creating my custom routing logic & overriding IRouteConstraint as specified here. This was an expensive solution as this logic would be executed every time.

Let us see how we can solve the above mentioned problems.

How

To get the solution I wanted, I had to make 2 changes.

  1. I had to register a customized routing pattern and
  2. I had to change controller action

Variable Routing

For ASP.NET MVC framework to catch the client name which the users would enter after my domain name, I will have to register a customized URL pattern.

Go to your MVC project and open solution explorer. Click on RouteConfig.cs file under App_Start directory and add the following code in RegisterRoutes method:

C#
routes.MapRoute("Customers", "{customer}", 
	new { controller = "Account", action = "Login" }, null);

Let's look at the parameters.

First parameter is the name you give to the routing pattern. I'm using "Customers", it can be anything. The next one is very important. This is the placeholder which would help us capture the customer name or any variable text passed by the user. The third parameter specifies the controller and action to pass the request to. Last parameter is used for any constraint to be added to the URL pattern.

Make sure to add the code before registering the default/generic route otherwise all the requests would be handled by the default/generic route and not your custom route.

If you are using the default RouteConfig.cs file from basic ASP.NET MVC template, then the RegisterRoutes code should look like this:

C#
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Customers", "{customer}", 
new { controller = "Account", action = "Login" }, null);
routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", 
                action = "Index", id = UrlParameter.Optional }
            );

Changing the Controller/Action Code

Go to Controllers directory and access the Accounts controller. Locate the Login(string returnURL) action method.

Change the method signature as below:

C#
public ActionResult Login(string returnUrl, string customer)

Note the second parameter added. This is where we will capture customer name entered by the user. Also, note that the parameter name should be exactly the same as specified while registering the custom route (in our case, it was {customer} and hence the parameter in the action method should be customer.

The code inside the Login action should now look like this:

C#
public ActionResult Login(string returnUrl, string customer)
{
 	if(ClientExists(customer)) //Check against DB or list or any other variable
	{
		//Do some custom logic
	}
	ViewBag.ReturnUrl = returnUrl;
	return View();
} 

Additional Resources

Refer to the links below for more information:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect thinkAzure.Net
India India
My name is Rohit Kukreti and have been in the software field for last 20+ years. Have always been working with the Microsoft Stack. Now a days my focus is on ASP.NET Core, MVC, Web API, Azure and SQL Server.
thinkAzure.Net

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1312991522-Sep-17 22:49
Member 1312991522-Sep-17 22:49 
QuestionAdding parameter to action: really needed? Pin
Member 1105843831-Oct-14 1:51
Member 1105843831-Oct-14 1:51 
GeneralMy vote of 1 Pin
Nikola Sivkov26-Oct-14 2:20
Nikola Sivkov26-Oct-14 2:20 
GeneralNice Tip Pin
Dukhabandhu Sahoo1-Oct-14 16:23
professionalDukhabandhu Sahoo1-Oct-14 16:23 
Thanks for sharing. Thumbs Up | :thumbsup:

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.