I am building a ASP.NET CORE Web API and using Swagger for the documentation. I have not been able to change the favicon. I have a swagger-ui directory under wwwroot where I have placed my favicon but the favicon is never there. Also, I am changing the favicon using favascript in a custom js file.
So, how does one change the favicon for Swagger?
You need to inject jscript as below:
1- Create /assets/js/docs.js as below:
(function() {
var link = document.querySelector("link[rel*='icon']") || document.createElement('link');;
document.head.removeChild(link);
link = document.querySelector("link[rel*='icon']") || document.createElement('link');
document.head.removeChild(link);
link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = '../assets/images/logo_icon.png';
document.getElementsByTagName('head')[0].appendChild(link);
})();
2- Load the script in your startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider)
{
app.UseSwaggerUI(
options =>
{
options.InjectJavascript("../assets/js/docs.js");
});
}
Note: Make sure you enable static files in your .NET Core Configure method.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider)
{
app.UseStaticFiles(); // For the wwwroot folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "assets/images")),
RequestPath = "/assets/images"
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "assets/js")),
RequestPath = "/assets/js"
});
}
This can also be achieved if you simply place your favicon.ico at the root within wwwroot folder: wwwroot/favicon.ico
. Being placed at the root, the favicon.ico be used as the default browser tab icon.
Of course as previously stated, you need to make sure you have app.UseStaticFiles();
in your Configure() method in order to serve the files within wwwroot.
Lastly also make sure you have the following in your .csproj file:
<ItemGroup>
<None Include="wwwroot\*" />
</ItemGroup>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With