Joydip Kanjilal
Contributor

How to work with static files in ASP.NET Core

how-to
Oct 28, 20196 mins
C#Microsoft .NETSoftware Development

Take advantage of the static files middleware in ASP.NET Core to serve HTML, CSS, JavaScript, and images to the client.

Man squeezed between file cabinets
Credit: Thinkstock

ASP.NET Core can serve static files—HTML files, images, JavaScript files, etc.—directly to clients. To enable ASP.NET Core to serve static files, you must use the framework’s Static Files Middleware in your application, and you must specify the necessary configuration. This article presents a discussion on how we can work with static files in ASP.NET Core.

Create an ASP.Net Core MVC project in Visual Studio

First off, let’s create an ASP.Net Core project in Visual Studio 2019. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.Net Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project. Optionally, select the “Place solution and project in the same directory” check box.
  6. Click Create.
  7. In the “Create a New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top.
  8. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either.
  11. Click Create. 

Following these steps should result in a new ASP.NET Core MVC project ready and waiting in Visual Studio. We’ll use this project in the sections that follow to work with static files in ASP.NET Core MVC.

Install the Static Files Middleware NuGet package

Now that we have created an ASP.NET Core MVC application in Visual Studio, the next thing you should do is install the necessary NuGet package. You must add the Microsoft.AspNetCore.StaticFiles middleware in the request pipeline to enable ASP.NET Core to serve static content.

You can install this package from NuGet Package Manager inside the Visual Studio 2019 IDE. Alternatively, you can run the following command to install this package via the .NET CLI.

dotnet add package Microsoft.AspNetCore.Rewrite

Configure the Static Files Middleware in ASP.NET Core

To enable ASP.NET Core MVC to serve static files, you must configure the Static Files Middleware. The following code snippet illustrates how you can configure the Static Files Middleware in the Startup class.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   app.UseStaticFiles();
   app.UseEndpoints(endpoints =>
   {
       endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
   });
}

Serve static files in ASP.NET Core

You’ll find the static files inside the wwwroot (content-root/wwwroot) folder. The static files are stored in folders named css, images, and js. All of these folders reside inside the wwwroot folder and are accessed using a relative path.

aspnet core static files 01 IDG

Viewing the wwwroot folder in Solution Explorer.

If the Static Files Middleware has already been installed and configured in your project, you can use the following URL to access an image named test.png:

https://localhost:44399/images/test.png

When you execute the application, you can see the image displayed in the web browser. Note the URL in the web browser.

aspnet core static files 02 IDG

A view of the city of Hyderabad, India. 

Now imagine that you’ll have to serve static files that reside outside of the wwwroot folder. Assume that there is a folder named IDGStaticFiles that contains the test.png file. The following code snippet illustrates how you can configure the Static Files Middleware to serve files that reside outside of the wwwroot folder.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseStaticFiles();
    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(),
            @"IDGStaticFiles")),
        RequestPath = new PathString("/StaticFiles")
    });
}

Enable directory browsing in ASP.NET Core

Directory browsing is a feature in web applications that allows users to browse the files and directories inside a specified directory. Note that for security reasons, this feature is disabled by default. You can enable directory browsing in an ASP.NET Core application by using the UseDirectoryBrowser extension method in the Configure method of the Startup class.

The following code snippet illustrates how you can add the services required to enable directory browsing to the request processing pipeline.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDirectoryBrowser();
}

Next, write the following code in the Configure method of the Startup class to use this middleware.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
   app.UseStaticFiles();
   app.UseStaticFiles(new StaticFileOptions()
   {
      FileProvider = new PhysicalFileProvider(
      Path.Combine(Directory.GetCurrentDirectory(),
      @"wwwroot")),
      RequestPath = new PathString("/IDGImages")
   });
  app.UseDirectoryBrowser(new DirectoryBrowserOptions()
  {
    FileProvider = new PhysicalFileProvider(
    Path.Combine(Directory.GetCurrentDirectory(), @"wwwrootimages")),
    RequestPath = new PathString("/IDGImages")
    });
 }

When you run the application and specify IDGImages in the path string, you’ll be able to see the contents of the wwwrootimages folder.

aspnet core static files 03 IDG

Directory browsing in action!

Secure file access in ASP.NET Core

Since there are no authorization checks by default, how can you secure access to the files that are served by ASP.NET Core? Note that the files that are present in the wwwroot folder are publicly available. To secure these files, it is imperative that you move these files to a different folder, i.e., to a folder that is outside the wwwroot folder. Lastly, to serve these files you can leverage an action method in your controller class that returns a FileResult instance.

Serve a default page in ASP.NET Core

Finally, you can take advantage of the UseDefaultFiles extension method to serve a default page. Here’s how you can configure this extension method in the Startup class.

public void Configure(IApplicationBuilder app)
{
    app.UseDefaultFiles();
    app.UseStaticFiles();
}

The UseFileServer extension method combines the capabilities of the UseStaticFiles, UseDefaultFiles, and UseDirectoryBrowser extension methods. If you would like to leverage all three capabilities using the UseFileServer extension method, you can write the following code in the Configure method of the Startup class.

app.UseFileServer(enableDirectoryBrowsing: true);
Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author