Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET MVC Dynamic Routing

0.00/5 (No votes)
1 Oct 2014 1  
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:

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:

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:

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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here