ASP.NET MVC Favicon Routing

To follow ASP.NET MVC best practices, you should put all static content files in the Content directory. However, this doesn’t play nice with favicon.ico, which is expected to be in the root of your domain. The solutions to this problem that I have seen online the most are to just put favicon.ico in the root of your project and tell the routing system to ignore it.

I came across a different solution: a custom route handler that can be used to redirect to the file in the Content directory:

internal sealed class StaticFileRouteHandler : IRouteHandler
{
    private string virtualPath;

    public StaticFileRouteHandler(string VirtualPath)
    {
        // make sure something was passed in
        if (string.IsNullOrEmpty(VirtualPath))
        {
            throw new ArgumentNullException("VirtualPath");
        }

        virtualPath = VirtualPath;
    }

    public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        HttpContext.Current.RewritePath(virtualPath);
        return new DefaultHttpHandler();
    }
}

Using this class, you can set up a route like the following, that will (internally) redirect requests for /favicon.ico and serve the file out of your Content directory.

RouteTable.Routes.Add(new Route("favicon.ico", new StaticFileRouteHandler("~/Content/favicon.ico")));

Kudos to RandomBen for the StaticFileRouteHandler class. I rewrite it a bit and adapted it for use in MVC to use the Content directory.

Leave a Comment