ASP.NET MVC twitter/myspace URL style routing

5 Comments

February 15, 2010 at 7:45 amCategory:ASP.Net MVC

Disclaimer : This tutorial is meant for beginners and for anyone who find it useful. The main purpose of this post to keep everything i find useful for future reference for myself and for others.


With ASP.Net MVC url routing feature its also desirable to have twitter/myspace url style routing for your application. Its also give simple and shorter personalize url for your user.

There is 2 steps to accomplish this, first is to define the url route in routing tables and second is to define route constrains.

Step 1 : Add following route map in Global.asax below your default routes to handle personalize user url


// to handle personalize user url
routes.MapRoute
(
"user",
"{url}",
new { controller = "Link", action = "url", url = "" }
);

In the above code I let my url method in Link controller handle the request , basically the method will check the supplied user is exist or not and do whatever necessary .

Now you need edit your default route because when you try invoke user url like http://yoursite.com/user it will processed by the default url and you will get  The resource cannot be found error. So we need add url constraints to our default url so that it only processed the non user url. To do that we need create Custom Route Constraints , see the following blog post by Guy Burstein. I get the following code there , create the following class in your project..


using System.Web.Routing;
using System.Web;
public class FromValuesListConstraint : IRouteConstraint
{
private string[] _values;

public FromValuesListConstraint(params string[] values)
{

this._values = values;

}

public bool Match(HttpContextBase httpContext,Route route,string parameterName,
RouteValueDictionary values,RouteDirection routeDirection)
{
// Get the value called "parameterName" from the
// RouteValueDictionary called "value"

string value = values[parameterName].ToString();

// Return true is the list of allowed values contains
// this value.

for (int i = 0; i < _values.Length; i++)
if (_values[i].Equals(value))
return true;

return false;
}

}

Now we are ready to modify our default route , change your default route to something similar to following code


routes.MapRoute
(
"Default",                                              // Route name
"{controller}/{action}/{id}",                           // URL with parameters
new { controller = "Home", action = "Index", id = "" },  // Parameter defaults
new { controller = new FromValuesListConstraint("Home", "Account","Link") }
);

The parameters values is to tell the route engine which url should be handle by this route definition. Now your personalize user url should work accordingly. If you the url does’t work get ASP.NET Routing Debugger from Phil Haacked and test your urls.