Back to: ASP.NET Core Tutorials For Beginners and Professionals
Static Files Middleware in ASP.NET Core Application
In this article, I will discuss how to Serve Static Files using Static Files Middleware in an ASP.NET Core Web Application with Examples. Please read our previous article before proceeding to this one, where we discussed the wwwroot folder in the ASP.NET Core Application.
Static Files Middleware in ASP.NET Core Web Application:
One of the most important features of almost all web applications should be the ability to serve static files directly from the file system. Serving these files efficiently is crucial for improving page load times and user experience. Static files such as HTML, Images, CSS, and JavaScript are important assets of a Web Application, and ASP.NET Core can serve these files directly to clients using Static Files Middleware.
However, ASP.NET Core does not serve static files by default. Enabling static file serving requires adding and configuring the UseStaticFiles() middleware in the application’s request pipeline. This middleware intercepts requests for static resources and returns them from the server without involving application logic.
Default Static File Directory: wwwroot
The default directory for static files in an ASP.NET Core application is the wwwroot folder, located in the project’s root directory. Only files placed within this directory are accessible to clients by default. Files stored outside of this folder remain inaccessible directly through URLs for security reasons. The location of the static file directory can be customized. For example, using the WebApplicationOptions instance, we can set a different directory path with the WebRootPath property.
Example to understand Static Files Middleware:
When we create a new ASP.NET Core Application with the Empty project template, by default, you will not find the wwwroot folder. The project structure of the ASP.NET Core Web Application with the Empty Project template is shown below.
As you can see in the above image, there is no such folder called wwwroot in our application. If you create the Project using a Razor Pages or MVC (Model-View-Controller) Project Template, then by default, the wwwroot folder will be created by Visual Studio.
Adding the wwwroot (webroot) Folder:
Let us first create the wwwroot Project Folder. To do so, right-click on the project and then select the add => new folder option from the context menu, and then provide the folder name as wwwroot. Once you create the wwwroot folder, your project structure should be as shown below.
Once you have created the wwwroot folder, add an Image file. Please download and paste the following image into the wwwroot folder, modifying the image name to MyImage.png.
Once you save the above image, your wwwroot directory looks as shown below.
Now run the application and navigate to the following URL. You need to replace the port number on which your application is running.
http://localhost:<portnumber>/MyImage.png
When you navigate to the above URL, you will not get the expected output; rather, you will get the following output.
You are not getting the output as expected because you don’t have any middleware that can serve the static files in the request processing pipeline.
How Do We Configure the Static Files Middleware in ASP.NET Core Application?
To handle the static resources in the ASP.NET Core Web Application, we need to configure a middleware called UseStaticFiles() into the application Request Processing Pipeline. The UseStaticFiles() middleware is an inbuilt Middleware provided by the ASP.NET Core Framework to handle the static files in an ASP.NET Core Web Application.
Let us Modify the Program class, as shown below, to register the UseStaticFiles() Middleware Component in the application’s Request Processing Pipeline.
namespace FirstCoreWebApplication { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); //Adding Static Files Middleware Component to serve the static files app.UseStaticFiles(); app.MapGet("/", () => "Hello World!"); //This will Run the Application app.Run(); } } }
With the above changes in place, now run the application and navigate to the URL: http://localhost:<portnumber>/MyImage.png, and you will see the output as expected, as shown in the below image.
How Does UseStaticFiles() Middleware Work Internally?
When a client requests a file, such as /logo.png, here’s how UseStaticFiles() processes the request:
Request Interception: When the UseStaticFiles() middleware is registered, it intercepts requests for file paths.
Path Matching: The middleware examines the request path. If the path corresponds to a file in the static file directory, i.e., wwwroot (or the custom folder specified with WebRootPath), it prepares the file for delivery.
Serving the File: If a matching file is found, the middleware sends it directly to the client. The file is sent with appropriate headers, including Content-Type, based on its extension.
Skipping Application Logic: By serving static files directly, the middleware bypasses the rest of the ASP.NET Core pipeline, improving performance by reducing unnecessary processing for static assets.
Caching and Security: To improve performance and control access, we can configure caching headers and set security rules for serving static files.
app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { // Cache static files for 30 days ctx.Context.Response.Headers["Cache-Control"] = "public,max-age=2592000"; } });
Return Not Found (404): If the requested file is not found in the wwwroot (or custom) folder, the pipeline can then handle the request as needed (e.g., returning a 404 page).
So, the UseStaticFiles() middleware in ASP.NET Core serves static files efficiently by intercepting requests, matching paths, and serving files directly to clients from the designated static file directory (default is wwwroot).
How Do We Create Our Own Webroot Folder in ASP.NET Core?
Let’s say we don’t want wwwroot as our webroot folder; instead, we want MyWebRoot as the webroot folder for our application. First, modify the wwwroot folder as MyWebRoot, and once you modify it, your project structure should be as shown below.
At this point, if you run the application, you will not get the output shown in the image below.
This is because, by default, the static files middleware will look for a folder named wwwroot that is not present in our application. But we don’t want wwwroot. We want the Static files middleware to look at the MyWebRoot folder to serve the static files such as CSS, Images, JS, etc. To do so, we need to tell the ASP.NET Core Framework to use MyWebRoot as the web root path. So, we need to set the WebRootPath property to MyWebRoot while creating the WebApplicationBuilder instance. Please modify the Main method of the Program class as shown below to configure the MyWebRoot folder as the webroot folder for our application.
namespace FirstCoreWebApplication { public class Program { public static void Main(string[] args) { //var builder = WebApplication.CreateBuilder(args); //Setting Custom Web Root Folder WebApplicationBuilder builder = WebApplication.CreateBuilder(new WebApplicationOptions { WebRootPath = "MyWebRoot" }); var app = builder.Build(); //Adding Static Files Middleware Component to serve the static files app.UseStaticFiles(); app.MapGet("/", () => "Hello World!"); //This will Run the Application app.Run(); } } }
After making the above changes, run the application, and you should get the expected output, as shown in the image below.
In the next article, I will discuss Configuring the Default Page in the ASP.NET Core Application with Examples. In this article, I explain how to serve static files using the static files middleware component in the ASP.NET Core Web application. I want to get your feedback on this article. Please post your feedback, questions, or comments about this Static Files Middleware Component in the ASP.NET Core Web Application article.
It’s missing parameter defaultFilesOptions in app.UseDefaultFiles(), if you want to display MyCustomPage1.html instead of default index.html…
//Adding Default Files Middleware to set the default page
app.UseDefaultFiles();
what a incredible nicely article
It is very simple explained article
this is very helpfull article.thank you