There is a lot of hidden magic that occurs in HostBuilder.ConfigureWebHostDefaults()
(that eventually calls ConfigureWebDefaults
). I would like to understand it better as there is no documentation that I can find about it.
This code seems to be loading some static files. What are static web assets and why do we need them? Is this something to do with embedding static assets into libraries for Blazor?
builder.ConfigureAppConfiguration((ctx, cb) =>
{
if (ctx.HostingEnvironment.IsDevelopment())
{
StaticWebAssetsLoader.UseStaticWebAssets(ctx.HostingEnvironment, ctx.Configuration);
}
});
A static asset is a file that's not directly associated with a web page or application. Think of the header images you see on pages that don't reside in the actual document — they're just there to provide a visual. Another example might be an embedded video.
Static files like JavaScript files, images, CSS files that we have on the file system are the assets that ASP.NET Core application can serve directly to clients. Static files are typically located in the web root (wwwroot) folder.
ASP.NET Core can serve static files—HTML files, images, JavaScript files, etc. —directly to clients. To enable ASP.NET Core to serve static files, you must use the framework's Static Files Middleware in your application, and you must specify the necessary configuration.
Static Web Assets are static files made available from a Razor Class Library (RCL):
An RCL may require companion static assets that can be referenced by the consuming app of the RCL. ASP.NET Core allows creating RCLs that include static assets that are available to a consuming app.
UseStaticWebAssets
inserts additional file providers (instances of StaticWebAssetsFileProvider
), using a manifest file ({environment.ApplicationName}.StaticWebAssets.xml
if not set via IConfiguration
) to determine a list of mappings from path to base path.
As an example, when using the ASP.NET Core Identity UI RCL, the manifest file for your app looks something like this:
<StaticWebAssets Version="1.0">
<ContentRoot BasePath="/Identity" Path="\path\to\.nuget\packages\microsoft.aspnetcore.identity.ui\3.0.0\staticwebassets\V4" />
</StaticWebAssets>
This all ends up with a CompositeFileProvider
being set for the IWebHostEnvironment.WebRootFileProvider
. This composite provider does two things:
wwwroot/
static files as usual (assuming default configuration).wwwroot/Identity
to the extracted NuGet package content folder for the Identity UI.As the code snippet from your question shows, this only happens when running in the Development
environment. When your app is published, the files in question get copied up into the wwwroot
folder, as though they were part of your app.
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