Using static files in ASP.NET Core

2 minute read

INDEX

  • Context
  • Static files
  • WWWroot folder
  • Enable the static files in the ASP.NET Core project
  • Reading static files

1. Context

Using static files in an ASP.NET Core project from the wwwroot folder using the IwebHostEnvironment’ interface inside the controller or service

2. Static file

The static files are the assets of the project, like HTML, CSS, JS, images, Excel, etc.

3. WWWroot folder

The static files are stored in the wwwroot folder in the project directory. The web root folder, i.e., wwwroot is the base path of the public and static resource files like Javascript (.JS), stylesheet (.css), etc.

4. Enable the static files in the ASP.NET Core project

‘UseStaticFiles’ in the startup will enable the static files to be served in the application.

Program.cs,

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.UseStaticFiles();

5. Reading static files

You can use the ‘IwebHostEnvironment’ interface to read the static files from the wwwroot folder in the ASP.Core project. Inject the interface through dependency injection from the startup class and access it in the controller or service class.

The below code snippet reads the static files from the web root folder using the IwebHostEnvironment interface.

UserController.cs,

using Microsoft.AspNetCore.Hosting;

IWebHostEnvironment WebHostEnvironment;

// User controller constructor
public UserController(IWebHostEnvironment webHostEnvironment) {
    WebHostEnvironment = webHostEnvironment;
}

// Get user list
[HttpGet]
public void GetUserList(string fileName){
  // Read the static file from the wwwroot folder
    var serverPath = WebHostEnvironment.WebRootPath + "\\image\\business\\" + fileName;
}

Thanks for reading the article on using static files in an ASP.NET Core project. Please feel free to drop your comments below, and you can follow us on Twitter (@Codetoliveblog) to receive the latest updates from this blog.

Leave a comment