Web Root and Static Files Middleware
Web Root and Static Files Middleware

Static Files Middleware In ASP .NET Core Applications

Every web application has many static files. Generally, every application has HTML, javascript, CSS files or images, which are referred to as static files.

ASP .NET Core web applications has middleware to serve these static files. Let’s have a closer look at some basics about the middleware and how it can be configured.

What is Web Root ?

When you create an ASP .NET Core web application, it has a WWWROOT directory. By default, this directory is the web root. A Web Root Directory is a directory which contains all the static files required for web application.

Default path of web root is {content-root-path}/wwwroot. Static files are accessible via a path relative to the web root. Below is the hierarchy of the folders inside wwwroot:

  • wwwroot
    • css
    • js
    • lib
    • images

Custom Web Root Path

Web root path can be customized by different techniques. Below code snippet shows multiple ways to set the web root path.

There is a setting in IWebHostEnvironment. This property is very specific to web applications (APIs, MVC app, Razor views app, etc.). This path is the relative path for public static resources (*.js, *.css, images, etc).

The default value is wwwroot folder inside the content root path. This folder must exist.

This value can also be set via code on the host builder. or via the environment variable ASPNETCORE_WEBROOT. In code, this can be set by calling UseWebRoot method.

Static Files Middleware

When an ASP .NET Core web application (MVC or Razor web app) is created using Visual Studio, the web app by default contains static file middleware configured in the request pipeline.

Once this middleware is configured, static files can be accessed be accessed by using relative paths. Below example shows how an image with path wwwroot/images/logo.png can be rendered.

<img src="~/images/logo.png" class="img" alt="My image" />


If the application needs to use authorization, then the order of authorization middleware and static files middleware has impact on how the files are served.

In .NET Core web application, every middleware adds some functionality to the previous middleware in the request pipeline.

  • So, if authorization middleware is placed before static files middleware, then anonymous access to static files is not allowed.
  • If authorization middleware is placed after static files middleware, then the static files can be served to anonymous requests.

I hope this information was helpful. Let me know your thoughts.

Leave a ReplyCancel reply