I'm building an MVC application that consists of entities that can be referenced by two different unique ID's, an ugly system generated ID, and a more user-friendly 5 character "Short Code". For example, I would like my end-users to be able to type the following url's in their browsers:
Again, both codes are unique. I have the routing for the first URL correctly set up. When the user enters that URL, they receive the proper page displaying the index page for the entity: PRJ201104.
How do I set up the route to handle the second scenario? Preferably there is a way to "trick" MVC into changing the value it passes to the controller from the short code to the project.
I would like a way to intercept the 5 character short code route, take the value provided and look it up in my entities table, then if I find a matching record I would like to either (in order of preference):
And if I don't find a matching Entity using that short code value I would let my standard route handling continue (so, for example, my "Error" and "Admin" controllers, which are both 5 characters as well but not Short Codes, will continue to work appropriately).
TIA
A custom route could do the job:
public class MyRoute : Route
{
public MyRoute(string url, object defaults)
: base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
{ }
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var rd = base.GetRouteData(httpContext);
var id = rd.Values["id"] as string;
if (id == null)
{
return rd;
}
// TODO: if you think that the id provided is a pretty id
// query the database to fetch the other id
if (IsPrettyId(id))
{
id = FetchCorrespondingId(id);
rd.Values["id"] = id;
}
return rd;
}
}
and then register this custom route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(
"Default",
new MyRoute(
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
)
);
}
Now inside the controller action you will always have the long ugly id:
public ActionResult Index(string id)
{
}