Search code examples
asp.netthemesmaster-pagesfavicon

Referencing favicon from inside folder using ASP.Net master page and themes


I have the following situation on my new ASP.Net page:

  • I am using a master page
  • I am using themes
  • I have pages in separate folders

I need to reference a favicon from my master page based on the current theme.

Unfortunately the ~App_Themes/Basic/Images/favicon.ico path resolves to http://example.com/folder/App_Themes/Basic/Images/favicon.ico.

How can I uniformly refer to my favicon.ico located in the App_Themes/Basic/Images/favicon.ico path from master page used by the following differently located pages:

  • ~/Home.aspx
  • ~/Secure/Dashboard.aspx
  • ~/Accounts/Login.aspx

Solution

  • Usually ASP.NET themes are limited to skin files and CSS files with all images referenced from the CSS file. In that scenario, the paths to images are relative from the CSS file.

    If you need a path to a file inside the current theme's folder relative from a page, you can use the Page.Theme property combined with the Page.ResolveUrl() method:

    <%= Page.ResolveUrl(String.Format("~/App_Themes/{0}/Images/favicon.ico", Page.Theme)) %>
    

    If you want to use that in a <link rel="shortcut icon"> element you can just put the code above inside the href attribute. Unless you have a <head runat="server">, in which case ASP.NET may throw an HttpException:

    The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

    This can be fixed by putting the <link> element inside an <asp:PlaceHolder> control:

    <head runat="server">
      <asp:PlaceHolder runat="server">
        <link rel="shortcut icon" href="<%= ... %>" />
      </asp:PlaceHolder>
    </head>