Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor CSS file is not served in .NET 8 preview 6 with the new project template

I have a started a new Blazor project for .NET 8 preview 6.

On the main index page, I have written the following code adding an optional parameter:

@page "/{optional?}"

<PageTitle>Home</PageTitle>

<h1>Home</h1>

Welcome to your new app.
@Optional

@code {
    [Parameter]
    public string Optional { get; set; }
}

Problem now is that on localhost the bundled CSS file is considered a parameter on GET request and the page has no style added.

localhost/ProjectName.styles.css 

here ProjectName.styles.css is considered on GET request when browser tries to fetch the stylesheet a string.

How can I move the generated CSS file to a subfolder?

Is there anyway to solve this problem without changing the code in Index.razor ?

like image 516
Ticu Ionut Avatar asked Oct 25 '25 05:10

Ticu Ionut


1 Answers

I reproduced your issue:

enter image description here

Blazor CSS file is not served in .NET 8 preview 6

If you input the urilocalhost/ProjectName.styles.css in address bar,it would go to your index page not the css file

If you comment this line :

app.MapRazorComponents<App>();

and try with the uri again,you would receive the css file

accroding to this doc:

CSS isolation occurs at build time. Blazor rewrites CSS selectors to match markup rendered by the component. The rewritten CSS styles are bundled and produced as a static asset. and this issue related

it makes no sense to determine where the static asset locates,but you could modify the request path to your staticfiles to avoid the confliction(If you want to keep the codes in Index page)

app.UseStaticFiles("/MyStaticFiles");

And modify the links in your app.razor:

.....
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <base href="/" />
    <link rel="stylesheet" href="MyStaticFiles/css/bootstrap/bootstrap.min.css" />
    <link rel="stylesheet" href="MyStaticFiles/css/bootstrap-icons/bootstrap-icons.min.css" />
    <link rel="stylesheet" href="MyStaticFiles/css/app.css" />
    <link rel="icon" type="image/png" href="favicon.png" />
    <link rel="stylesheet" href="MyStaticFiles/BlazorApp2.styles.css" />
    <HeadOutlet />
</head>
......

Now it works : enter image description here

like image 56
Ruikai Feng Avatar answered Oct 26 '25 19:10

Ruikai Feng



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!