domaindrivendev / Swashbuckle.AspNetCore

Swagger tools for documenting API's built on ASP.NET Core
MIT License
5.21k stars 1.3k forks source link

Support 'favicon.ico' natively #2229

Open julealgon opened 2 years ago

julealgon commented 2 years ago

I'm trying to customize the favicon used by swagger UI page and it only allows using specific PNG images, namely:

However, my application already contains a favicon.ico in the root folder that contains these 2 sizes, so having to extract the individual images and duplicating them just for the swagger page seems less than ideal to say the least.

When searching topics related to "favicon" it seems that using the '.ico extension is far more standard than having it as individual PNG images like what the index page here does: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/a53d463a37d339ed1555c729446846b92f91a53c/src/Swashbuckle.AspNetCore.SwaggerUI/index.html#L8-L9

Is there a way to extend support for favicon.ico so it is easier to replace the original icon without having to create duplicate assets?

0xced commented 1 year ago

It's possible to update the favicon dynamically with some javascript:

(function() {
    var link = document.createElement('link');
    link.rel = 'icon';
    link.type = 'image/x-icon';
    link.href = '/favicon.ico';
    [...document.querySelectorAll("link[rel='icon']")].map(e => e.remove());
    document.head.appendChild(link);
})();

(Adapted from How do you change the Swagger favicon? code by @barsham on Stack Overflow.)

Then serve this favicon-update.js file however you want (from a static file, from a controller, ...) and configure the swagger UI options to inject this piece of javascript:

app.UseSwaggerUI(options =>
{
    options.InjectJavascript("/favicon-update.js");
});

While this is a nice workaround that avoids duplicating assets it would still be nice to have a real solution where the favicon could be configured through the options.