简体   繁体   中英

Serve static files in blazor hosted project

It is a pretty simple Task, I want to use images in my razor pages which are located in wwwroot/css/images and use it in html like this.

<img src="~/css/images/logo.png"/>

In a normal ASP.Net Core application I would just add app.UseStaticFiles() in the Configure method, but since this is a blazor hosted application, it changes nothing.

I also tried adding the app.UseStaticFiles() in the server project, but with no success either.

If you want to try it out yourself just create a blazor-hosted project from the templates and try to serve/display images like I did.

Blazor serves static file just fine. The issue you're having is the syntax you're using to reference the file. You just need to drop the ~ symbol.

<img src=“/css/images/logo.png” />

One precision about that...the static file root for anything in blazor starts at the wwwroot folder. wwwroot is simply taken for granted and is omitted in the actual path you need to use to ask for a static file. using :

"/css/images/logo.png"

could also be expressed :

"css/images/logo.png"..I'm pretty sure.

If you are in a Razor Class Libray...there is also a wwwroot for the Razor Class Library itself. When used is a Blazor Wasm Client the filepath for any static file in the RCL becomes :

"_content/[RCL assembly name]/css/images/logo.png"

Note that even for classes and stuff you implement inside the Razor Class Library itself, even you are in that library defining stuff...static files in your own wwwroot inside a Razor Class Library are called using the "_content/[RCL assembly name]" prefix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM