• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Thursday, August 20, 2020

Static Files Middleware in ASP.NET Core

 Admin     August 20, 2020     .Net, .Net Core, Asp.Net, C#     No comments   

In this article, I am going to discuss how to serve static files using Static Files Middleware in ASP.NET Core Application. Please read our previous article before proceeding to this article where we discussed the Request Processing Pipeline in ASP.NET Core Application. As part of this article, we are going to discuss the following pointers in details.
  1. Where do we need to store the static files in ASP.NET Core?
  2. What is wwwroot folder in ASP.NET Core?
  3. How to Configure Static Files Middleware in ASP.NET Core Web Application?
  4. What is the use of the UseFileServer() Middleware component?
One of the most important features almost all web applications should have the ability to serve the static files directly from the file system. The static files such as HTML, Images, CSS, and JavaScript are the important assets of an application and ASP.NET Core can serve these files directly to the clients. But the important point that you need to keep in mind by default the ASP.NET Core cannot serve these static files. Some configuration is required in order to enable the ASP.NET Core to serve these static files directly.

Where do we need to store the static files in ASP.NET Core?
In ASP.NET Core, the default directory or location for the static files is wwwroot (webroot) folder and moreover, this folder or directory should be present in the root project folder. By default, this is the only place where the ASP.NET Core application can serve the static files directly. But we can change this default behavior by using the UseWebRoot method that we will discuss in our upcoming articles. In this article, we are going with the default behavior.

Adding the wwwroot (webroot) folder:
Right-click on the project and then select add => new folder option and then provide the folder name as wwwroot.

Once you created the wwwroot folder, let’s add an HTML file within that folder. To do so, right-click on the wwwroot folder and then select add => new item which will open add new item window. From that window select the HTML template, provide a name such as “MyCustomPage1” and then click on the Add button as shown in the below image.
Static Files Middleware in ASP.NET Core

Once you click on the Add button, then it will add the HTML page within the wwwroot directory. Open the HTML file and then copy and paste the following code in it.
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>Serving Static Files in ASP.NET Core</h1>
</body>
</html>
Following is the directory structure of your application:
Static Files Middleware in ASP.NET Core Directory Structure

Following is the Configure() method of the Startup class.
Static Files Middleware in ASP.NET Core Configure Method

Now run the application and navigate to the following URL. The point that you need to remember is the port number may be different in your machine.

http://localhost:59119/MyCustomPage1.html

So when you navigate to the above URL, you will not get the output as expected. Here you are getting the response from the middleware which is registered using the Run() extension method. The reason why we are not getting the output as expected because we don’t have any middleware which can serve the static files in the request processing pipeline.

Configuring Static Files Middleware:
The ASP.NET Core provides a middleware called UseStaticFiles() which can be used to serve the static files.

Let us Modify the Configure() method of the Startup class in order to add the UseStaticFiles() middleware to the request processing pipeline of the application as shown below.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    //Adding Static Files Middleware to serve the static files
    app.UseStaticFiles();
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Request handled and response generated");
    });
}
Now run the application and navigate to the following URL and you will see the output as expected that is coming from the static HTML file.

http://localhost:59119/MyCustomPage1.html

Setting the Default Page:
Most of the web applications have a default page such as index.htm(l) or default.htm(l) as their startup page as it is easy to remember. This is the web page that is going to be displayed when a user visits the root URL of that application. For example, if you have a page with the name index.html and you want that page to be your default page so that whenever any user visits your root URL, then that page is going to be displayed.

Let’s add a new HTML File with the name index.html within the wwwroot folder of your project. Once you add the index.html file then copy and paste the following HTML code in it.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>This is the Default Page</h1>
</body>
</html>
Now run the application and navigate to the root URL as shown below.

http://localhost:59119/

Output:
Serving Static Files in ASP.NET Core

You are getting the response from the middleware which is registered using the Run() extension method. In order to serve the index.html page as the default page of your application, you need to add another middleware i.e. UseDefaultFiles() middleware into the request processing pipeline. So, modify the Configure() method of the Startup class as shown below to use the UseDefaultFiles() middleware which will set the default page for your application.
Setting Default Files in ASP.NET Core

Now run the application and you will see the output as expected.

Note: You need to add the UseDefaultFiles() middleware before the UseStaticFiles() middleware in order to serve the default file. The point that you need to remember is the UseDefaultFiles() middleware is just a URL rewriter and it never serves the static files. The job of this middleware is to simply rewrite the incoming URL to the default file which will then be served by the Static Files Middleware.

The UseDefaultFiles() middleware will search the wwwroot folder for the following files.
index.htm
index.html
default.htm
default.html 
This is the default behavior. But if you want then you can also change this default behavior. For example, if you want MyCustomPage1.html page as the default page instead of the index.html then you need to modify the Configure() method of the Startup class as follows.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    //Specify the MyCustomPage1.html as the default page
    DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
    defaultFilesOptions.DefaultFileNames.Clear();
    defaultFilesOptions.DefaultFileNames.Add("MyCustomPage1.html");
    //Adding Default Files Middleware to set the default page 
    app.UseDefaultFiles();
    //Adding Static Files Middleware to serve the static files
    app.UseStaticFiles();
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Request handled and response generated");
    });
}
Now run the application and you will see the output as expected that is coming from the MyCustomPage1.html file. If you still see the output from the index.html page then it may be sue to cache so just try to reload the page. If still, you are not getting the data from the MyCustomPage1.html file then just restart the visual studio.

What is the use of the UseFileServer() Middleware component?
The UseFileServer() middleware components combines the functionality of UseStaticFiles, UseDefaultFiles and UseDirectoryBrowser middleware. We already discussed the UseStaticFiles and UseDefaultFiles middleware. The DirectoryBrowser middleware as the name says enables the directory browsing which allows the users to see the files which are stored in a specific directory. In our example, we can replace the UseStaticFiles() and UseDefaultFiles() middlewares with the UseFileServer() Middleware as shown below.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    // Use UseFileServer instead of UseDefaultFiles & UseStaticFiles
    FileServerOptions fileServerOptions = new FileServerOptions();
    fileServerOptions.DefaultFilesOptions.DefaultFileNames.Clear();
    fileServerOptions.DefaultFilesOptions.DefaultFileNames.Add("MyCustomPage1.html");
    app.UseFileServer(fileServerOptions);
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Request handled and response generated");
    });
}
Now run the application and you will see the output as expected.

In the next article, we are going to discuss the Developer Exception Page Middleware in detail. Here, in this article, I try to explain how to serve static files using Static Files Middleware in the ASP.NET Core application. I would like to have your feedback about this article. Please post your feedback, question, or comments about this article.

Summary:
I hope this post will be helpful to understand the concept of Static Files Middleware in ASP.NET Core
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • ASP.NET State Management
    State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in ...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...
  • Navigation Menus in ASP.NET Core
    In this article, I am going to discuss how to create Responsive Navigation Menus in ASP.NET Core Application using bootstrap and JQuery. P...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • ViewModel in ASP.NET Core MVC
    In this article, I am going to discuss ViewModel in ASP.NET Core MVC application with an example. Please read our previous article before ...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape