How to add a favicon under /favicon.ico in Orchard Core - Orchard Core Nuggets

Zoltán Lehóczky's avatar
Orchard Core Nuggets, Orchard Core, Favicon, ASP.NET Core, Click to deploy improvements, autoroute container routing - This week in Orchard (24/04/2020)

Every website needs a favicon of course and you can easily add one to your Orchard Core site from a theme or module with a link tag in a template. However, there's a catch: Certain browsers will still search for it (as a first attempt) under the path /favicon.ico. This can be a tiny bit detrimental to the client-side performance, and show up as annoying errors in your logs. So what can you do to serve a favicon under that path too?

You could do e.g. the following:

  • Add an actual file to your web project's wwwroot folder directly. This will work but you'll most likely have more than one icon for the site, and you'll keep them in a theme. So having two places with icons is less than ideal.
  • Serve the same file that you have in your theme with a middleware or something. Doable but you'd teach the affected browsers that what they're doing is actually acceptable :).
  • Redirect a /favicon.ico request to the actual favicon. This is what we'll do with the code snippet below!

Open up your theme's Startup class and add this to its Configure() method (or add the method first if you haven't used it otherwise):


public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) =>
    app.Map("/favicon.ico", appBuilder => appBuilder.Run(context =>
    {
        context.Response.Redirect("/My.Theme/favicon.ico", true);
        return Task.CompletedTask;
    }));

As you can see this simple snippet will listen on the /favicon.ico path and redirect the client to the favicon you have in your theme (in this case we assumed it's in the root of your theme's wwwroot folder but of course it can be in any subfolder). Very simple!

Did you like this post? It's part of our Orchard Core Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard Core tips and let us know if you have another question!

No Comments

Add a Comment