我需要能够根据请求中的上下文从MVC返回不同的favicon图像。我尝试了一些但似乎无法拦截favicon.ico
的请求并将自定义ico文件写入响应。我尝试过自定义路由处理程序和自定义http处理程序。在这两种情况下,他们似乎永远不会被召唤。有人可以帮助解决问题吗?
自定义路由处理程序
这是路由处理程序代码
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();
}
}
以下是global.asax
中添加的路由配置routes.Add(new Route("favicon.ico", new FaviconRouteHandler()));
自定义HTTP处理程序
这是http处理程序代码
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();
}
}
这是添加到system.webserver的处理程序注册。另一个被添加到web.config文件中的system.web
<add name="FaviconHandler" verb="GET" path="favicon.ico" type="MyProject.FaviconHttpHandler"/>
上下文:我正在使用VS 2013,MVC4