Serving static files in ASP .NET Core
.NET Core .NET

Serving static files in ASP .NET Core

Mishel Shaji
Mishel Shaji

By default, ASP .NET Core is not configured to serve static files such as CSS, Js or HTML over HTTP for a client request.

Serving Static files

The ASP .NET Core application must be configured to serve static files to the clients.

As we have modified the Configure method in our previous examples, it’ll be good to create a new project for this example. Or just make sure that the configure method in Startup.cs looks similar to the one shown below.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
      }
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseCookiePolicy();
      app.UseMvc();
}

Serving static files from web root

By default, static files are saved in the web root (wwwroot) directory.

If your project is targeted in .NET Core version below 2x, you need to install Microsoft.AspNetCore.StaticFiles middleware manually.

To understand this, create a new HTML file named myfile.html in the wwwroot folder (Right-click on wwwroot ->Add -> New Item -> HTML Page) and add the following code.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>A static HTML Page.</h1>
</body>
</html>

Run the project and navigate to https://localhost:<port>/mypage.html.

Now comment the following line or from Configure() method in Startup.cs and try to access the page again.

//app.UseStaticFiles();

You’ll get a 404 error page.

Uncomment the above line.

app.UseStaticFiles();

The Static File Middleware doesn’t provide authorization checks to any files served by it.

Serving static files outside web root

To understand how to serve static files from outside the web root, Right-click on the project -> Add -> New Folder and name it MyStaticFiles. Now add a new HTML page named page.html to the folder in the same way we have created mypage.html just before and add the following code to it.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>A static page outside web root</h1>
</body>
</html>

Run the project and navigate to https://localhost:<port>/MyStaticFiles/page.html.

You’ll get a 404 error page.

This shows that static files outside the web root will not be served without configuring the application.

To use static files from outside the web root folder, modify the UseStaticFiles middleware as shown below.

app.UseStaticFiles(new StaticFileOptions{
    FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(
        System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "MyStaticFiles")),
    RequestPath = "/StaticFiles"
}); 

Now you will be able to access static files from the directory by navigating to https://localhost:<port>/StaticFiles/page.html

Setting HTTP response headers

HTTP headers can be set to the static files using the StaticFileOptions object. Here’s an example.

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = context =>
      {
            context.Context.Response.Headers.Append("Cache-Control", $"public, max-age=300");
      },
      FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(),"MyStaticFiles")),
      RequestPath = "/StaticFiles"
});