Categories
Technology

Static Image in Blazor – Inside and Outside Web Root

This article explains how to display a static image in the Blazor component. In ASP.NET Core  static files are served by Microsoft.AspNetCore.StaticFiles middleware. First, let’s look at the general way to display the image in the Blazor component.

Inside the Web Root

To display a static image in the Blazor component, first, it must store the image in any folder under the wwwroot file. It can be accessed by the relative path. To serve a static image, you need to use the app.UseStaticFiles () method in the start.Configure file.

The following is the Blazor component code. Here the image is obtained from {applicationFolder} /wwwroot/Image/InsideWebRoot.png.

@page “/”
<h3> Display Image in Blazor</h3>
<div>
    <img  src=”/Image/InsideWebRoot.png”   />
</div>
@code {
}

Outside the Web Root

The static file can also be served outside the web root. Consider the following image, here the StaticFilesFolder/Image is created outside the wwwroot folder.

Static Image

To serve this, you first need to configure the UseStaticFiles () method in the Startup.cs file. In the following code, UseStaticFiles uses FileProvider to locate the static file. PhysicalFileProvider is used to access the physical path. The request path is set to “/staticFiles”, which is mapped to the static file.

public void  Configure(IApplicationBuilder  app, IWebHostEnvironment env)
{
    app.UseStaticFiles();
 
    app.UseStaticFiles( new StaticFileOptions
    {
FileProvider = new  PhysicalFileProvider(
       Path. Combine(Directory . GetCurrentDirectory(), “StaticFilesFolder” )),
RequestPath = “/StaticFiles”
    });
}

The following is the Blazor component code. The static image path in the img tag is assigned as “/StaticFiles/Image/OutsideWebRoot.png”. The /StaticFiles is a RequestPath that is configured in the startup.cs file. So the following code will show the static image that is outside the web root.

@page “/”
<h3> Display Image in Blazor</h3>
<div>
    <img  src=”/StaticFiles/Image/OutsideWebRoot.png”  />
</div>
@code {
}

This article explains how to display a static image in Blazor Component.

If you have questions, please leave a comment.