by aanund
12. February 2011 01:34
Continuing in the same topic as the languagehandler, this RouteHandler allows you to define ‘shortcuts’ outside of the Routing system (for instance in a database). To use it, you add a catch-all route with this RoutHandler (preferrably in conjunction with a special controller to handle 404’s).
IShortCutProvider shortCutProvider = ...;
Route possible404 = new Route(
"*",
new RouteValueDictionary(
new { controller = "fault", action = "404" }
),
new RedirectRouteHandler(shortCutProvider)
);
routes.Add(possible404);
Uses a simple interface to check for available shortcuts.
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace austrheim
{
public class RedirectRouteHandler : MvcRouteHandler
{
private IShortCutProvider _shortCutProvider;
public RedirectRouteHandler(IShortCutProvider shortCutProvider)
{
_shortCutProvider = shortCutProvider;
}
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string newUrl;
if (_shortCutProvider.TryGetShortCut(requestContext.HttpContext.Request.Url, out newUrl))
{
return new RedirectHandler(newUrl);
}
return base.GetHttpHandler(requestContext);
}
}
public interface IShortCutProvider
{
bool TryGetShortCut(Uri requestUri, out string newUrl);
}
public class RedirectHandler : IHttpHandler
{
private string newUrl;
public RedirectHandler(string newUrl)
{
this.newUrl = newUrl;
}
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext httpContext)
{
httpContext.Response.StatusCode = 301;
httpContext.Response.RedirectLocation = newUrl;
}
}
}
When a url is entered that does not match any routes, it will trickle down to the catch-all route.
The catch-all route then checks if a shortcut is found, and the viewer will be redirected to the shortcuts destination.