If you are using MVC, in some file you will be generating the route record. Something similar to:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
What we are going to do is create a new generic route record over the Default route:
string name = "GenericUrl";
string url = "{generic}";
object defaults = new { controller = "Common", action = "GenericUrl" };
object namespaces = new[] { "SampleWebApp.Controllers" };
var route = new GenericPathRoute(url, new MvcRouteHandler()) {
Defaults = new RouteValueDictionary(defaults),
DataTokens = new RouteValueDictionary()
};
if (namespaces != null) {
route.DataTokens["Namespaces"] = namespaces;
}
routes.Add(name, route);
This rule will capture all the url's and analyze them in a later function. If they are "known" you can redirect the destination, and if they are not, the execution will continue.
To analyze the url's we need a new class that derives from Route and we have to overload the GetRouteData method:
public class GenericPathRoute : Route {
public GenericPathRoute(string url, IRouteHandler routeHandler) : base(url, routeHandler) { }
public GenericPathRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler) { }
public GenericPathRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler) : base(url, defaults, constraints, routeHandler) { }
public GenericPathRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler) { }
public override RouteData GetRouteData(HttpContextBase httpContext) {
RouteData data = base.GetRouteData(httpContext);
if (data != null) {
var slug = data.Values["generic"] as string;
if (slug == "xxx") {
data.Values["controller"] = "Home";
data.Values["action"] = "ProductDetails";
data.Values["productid"] = 1;
return data;
}
}
return data;
}
}
Within the method the slug variable rescues the content of the "generic" url and you can tweak it as you see fit. Whether parsing, searching in database, etc ...
The "productid" index is an example. In this case, it corresponds to the name of the controller action parameter.
public class HomeController : Controller {
public ActionResult ProductDetails(int productid) {
...
}
}