What are ASP.NET Core Static Web Assets?

Viewed 9357

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);
    }
});
1 Answers

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:

  1. Processes the wwwroot/ static files as usual (assuming default configuration).
  2. Delegates any files requested from 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.

Related