Wednesday, September 16, 2009

ASP.NET favicon.ico routing to deep link

After seeing some errors in my application log complaining about a non existing business object with id favicon.ico, and being sure that I had a <link href="/resources/images/favicon.ico" rel="shortcut icon" /> tag in my header section, I realized that old non-standard-compliant browsers do a request for the hard-coded /favicon.ico url. So I wanted to add a route in my route table to redirect these requests to the proper icon location. Unfortunately, there is no public StaticFileHandler available with a virtual path in its constructor, so I had to built them myself. The following couple of lines do the trick:

Registering the routes in the application startup:

routes.Add(new Route("favicon.ico", new StaticFileRouteHandler("~/Resources/images/favicon.ico")));
// generic, catch-all rule, caused the error for favicon.ico
routes.Add(Routes.BusinessObject, new Route(
string.Format("{{{0}}}", RouteParameters.BusinessObjectIdentifier),
new CustomRouteHandler("~/Pages/BusinessObjectDetails.aspx")));


The StaticFileRouteHandler to serve the the static file from the request.

public class StaticFileRouteHandler : IRouteHandler
{
public string VirtualPath { get; set; }
public StaticFileRouteHandler(string virtualPath)
{
VirtualPath = virtualPath;
}

#region IRouteHandler Members
public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext)
{
HttpContext.Current.RewritePath(VirtualPath);
return new DefaultHttpHandler();
}
#endregion
}

No comments:

Share