Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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.

like image 664
Leonardo Tanoue Avatar asked Apr 20 '26 00:04

Leonardo Tanoue


2 Answers

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.

like image 92
Ben Sampica Avatar answered Apr 21 '26 16:04

Ben Sampica


For anyone else... I had the exact same issue with a .net 6 blazor server app. For me it came down to the fact that I had changed the project name but the reference to {project}.styles.css in _Layout.cshtml was still pointing to the old project name. Simply updating {project} here to the correct project name fixed my issue.

like image 31
srHunter Avatar answered Apr 21 '26 15:04

srHunter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!