Alexander Zwitbaum
Alexander Zwitbaum

Reputation: 4846

Access ASP.NET Core Blazor static files from asset in css

The new MapStaticAssets feature in .NET 9.0 optimizes the delivery of static asset files, solving various problems such as preventing browsers from using old or stale assets and enabling the serving of compressed asset versions. To use a static file from an asset in a Razor component, you simply need to declare its path using the @Asset directive. Example:

<img src="@Assets["/images/picture.jpg"]" />

However, how do you access your file from an asset when not in a Razor component, such as when setting a background image in CSS? Example:

.section { background-image: url("images/background.jpg"); }

Upvotes: 0

Views: 298

Answers (1)

topsail
topsail

Reputation: 3130

When you switch to the new static assets middleware with MapStaticAssets() you can add a component called ImportMap to your app.Razor, making it available throughout your application to map static assets when rendering blazor components

in App.razor:

<head>    
  <ImportMap />
</head>

You can then view the page source of your rendered pages to see the "mapped" assets with their finger-printed filenames (such as my-image.doc2ew1kj4.png) in order to verify that it is all working as expected.

References: static-asset-delivery-optimization, static-asset-delivery-in-server-side-blazor-apps, and import-maps

Upvotes: 0

Related Questions