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

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 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 tips and let us know if you have another question!

Send us new blog feeds

Noticed that a blog's feed is missing from the list? 

We would love to add that to the feed list, so please don't hesitate to inform us on the following e-mail adress:

crew@lombiq.com

See our privacy policy.