blazorblazor-server-sideblazored

Blazor Server - static files don't link in non-DEV environments


It seems in a standard Blazor server app, the _content folder items are not being referenced correctly for anything other than the Development environment. As an example, this reference fails in any non-dev environment:

from _Host.cshtml:

<link href="_content/Blazored.Typeahead/blazored-typeahead.css" rel="stylesheet" />

To Repro, using Blazored-toast lib as an example (but any static file refs seem to have this issue):

Create a new Blazor Server project (dotnet new blazorserver)

  1. Add all necessary Blazored / Toast elements, including code to demo a toast message
  2. Test that toast is working Change launchSettings.json ASPNETCORE_ENVIRONMENT to Staging, Production, or anything other than Development
  3. Run program again (using ISS Express local debug), and notice the css formatting is not correct
  4. Change debug settings to use Kestrel instead (change IIS Express drop-down to BlazorApp1 or similar)
  5. Notice with kestrel, css is working fine

What am I missing that would allow this reference to work in other environments?


Solution

  • Consuming static assets from a Razor Class Library works out of the box when the application gets published. You just have to include the static content via <link href="..." /> as you did.

    However, when running the app from the build output (dotnet run) or via F5 in Visual Studio you have to ensure that the StaticWebAsset feature is enabled for the given environment.

    It is enabled by default for the development environment only. You can turn on the feature unconditionally by ensuring you called UseStaticFiles and calling UseStaticWebAssets in the Program.CreateHostBuilder.

    So, ensure that you consuming app has :

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ...
    
        app.UseStaticFiles();
    
        ...
    }
    

    and in your Program.cs you should have

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStaticWebAssets();
                webBuilder.UseStartup<Startup>();
            });