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