Search code examples
cssblazor-server-side.net-6.0

.Net 6 Blazor Server-Side CSS Isolation not working


I created a new .NET 6 Blazor Server-side project and made a couple of changes. I have a couple of files using CSS isolation (like Contact.razor + Contact.razor.css).. In the _Layout.cshtml page the template added the following:

<link href="CustomerPortal.styles.css" rel="stylesheet" />

Where CustomerPortal is my Project Name. I can see the file is generated correctly under "CustomerPortal\CustomerPortal\obj\Debug\net6.0\scopedcss\projectbundle\CustomerPortal.bundle.scp.css" and "C:\Data\Git\WebApps\CustomerPortal\CustomerPortal\obj\Debug\net6.0\scopedcss\bundle\CustomerPortal.styles.css" BUT when I run the project, both with Kernel or IIS Express, I get a 404 not found for the CSS, if I try to manually navigate to the CSS I also can't find it. Any ideas? My csproj doesn't have any flags that would affect it.


Solution

  • Edit: There is a new extension as part of the minimal setup in .NET 7, and backported to newer versions of .NET 6 as well.

    Both in .NET 7 and .NET 6 you can now do:

    builder.WebHost.UseStaticWebAssets();

    Old answer:

    You've got a couple options here to resolve this depending on the approach you want to take. I think we've figured out why it's happening, but UseStaticWebAssets() seems to not be supported for the new minimal startup code. So, here's your options I can think of off the top of my head.

    1. Migrate your code back to the "old" way of doing application startup. This is still a supported and completely valid approach as there's edge cases that aren't supported (like this one).
    2. Pass a new WebApplicationOptions to the CreateBuilder() method and, depending on environment, look for the static files in a separate (and correct) location. See some examples here.
    3. With the existing builder, check the environment and use the StaticWebAssetsLoader to load static web assets.

    A complete example of #3

    if (builder.Environment.IsEnvironment("Local"))
    {
        StaticWebAssetsLoader.UseStaticWebAssets(builder.Environment, builder.Configuration);
    }
    

    That being said - I'd imagine they'll plug this hole eventually and provide parity for UseStaticWebAssets(). You can see the progress of this effort in this open GitHub issue.