1

I need to be able to return different favicon images from MVC based on context in the request. I have tried a few things but can't seem to intercept requests for favicon.ico and write a custom ico file to the response. I've tried a custom route handler and a custom http handler. In both cases, they never seem to get called. Can someone help shed some light on the problem?

Custom Route Handler

Here is the route handler code

public class FaviconRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var path = "/favicon.ico"; // business logic added here to set dynamic source path

        var context = HttpContext.Current;

        context.Response.ContentType = "image/x-icon";
        context.RewritePath(path);

        return new DefaultHttpHandler();
    }
}

Here is the route configuration added in global.asax

routes.Add(new Route("favicon.ico", new FaviconRouteHandler()));

Custom HTTP Handler

Here is the http handler code

public class FaviconHttpHandler : IHttpHandler, IRouteHandler
{
    public RequestContext RequestContext { get; set; }

    public FaviconHttpHandler(RequestContext requestContext)
    {
        this.RequestContext = requestContext;
    }

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        var path = "/favicon.ico"; // business logic added here to set dynamic source path

        var response = context.Response;
        response.ContentType = "image/x-icon";
        response.WriteFile(path);
        response.End();
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        throw new NotImplementedException();
    }
}

Here is the handler registration added to system.webserver. Another was added to system.web in the web.config file

  <add name="FaviconHandler" verb="GET" path="favicon.ico" type="MyProject.FaviconHttpHandler"/>

For context: I am using VS 2013, MVC4

JoeGeeky
  • 3,746
  • 6
  • 36
  • 53
  • Since the favicon is cached you have to force the browser to actually download a new one check this question http://stackoverflow.com/questions/2208933/how-do-i-force-a-favicon-refresh – Robert Aguilar Jul 26 '14 at 19:01
  • @RobertAguilar I am using Fiddler so I am completely skipping the cache. I still don't see the handler getting hit. I am wondering if there is a reserved behaviour related to favicon.ico – JoeGeeky Jul 26 '14 at 19:19

0 Answers0