Search code examples
asp.net-mvchttphandlerfavicon

MVC Serving Favicons based on Domain


now I have a web application that will be published on multiple domains and I want to support different favicon based on domain

what I had done is :

** Added a handler in web.config called “favicon”, for any request for a file called “favicon.ico”

<system.webServer>
<handlers>
<add name="favicon" verb="*" path="favicon.ico" type="namespace.FaviconHandler, MyApplication" />
// other handlers
</handlers>
</system.webServer>

** then added class that supports the IHttpHandler interface

public class FaviconHandler : IHttpHandler
    {
        public void ProcessRequest(System.Web.HttpContext ctx)
        {
            string path = getFavIconPath(ctx.Request.Url.Host.ToLower());
            string contentType = "image/x-icon";
            path = ctx.Server.MapPath(path);

            if (!File.Exists(path))
            {
                ctx.Response.StatusCode = 404;
                ctx.Response.StatusDescription = "File not found";
            }
            else
            {
                ctx.Response.StatusCode = 200;
                ctx.Response.ContentType = contentType;
                ctx.Response.WriteFile(path);
            }
        }
        private string getFavIconPath(string domain)
        {

            if (!string.IsNullOrEmpty(domain))
            {

                if (domain.Contains("abc.com")))
                    return "favicon.ico";
                else
                    return "favicon2.ico";
            }
            return "favicon.ico";
        }
    }

The problem is .. it's not working well.. What I miss?? Thanks in advance


Solution

  • Another way could be to keep all icon files named with domain names like -

    images
        - abc.com.ico
        - def.com.ico
    

    Make a basecontroller and set a ViewBag property in its OnActionExecuting (override it) with hostname -

    public override void OnActionExecuting(ActionExecutingContext ctx)
    {
        base.OnActionExecuting(ctx);
        string host = HttpContext.Request.Host.Value;
        ViewBag.Host = host;
    }
    

    And in your master layout set favicon link like -

    <link rel="icon" href="~/images/@(ViewBag.Host).ico"/>