ASP.NET Core 2.0 Static Files

Problem

How to serve static content (HTML, CSS, JavaScript, Images) from ASP.NET Core application.

Solution

Modify the Configure() method in Startup class to use middleware for static files.

  1. public void Configure(  
  2.     IApplicationBuilder app,  
  3.     IHostingEnvironment env)  
  4. {  
  5.     app.UseStaticFiles(); // for files in wwwroot folder  
  6.   
  7.     app.UseStaticFiles(new StaticFileOptions() // for files in content folder  
  8.     {  
  9.         FileProvider = new PhysicalFileProvider(  
  10.             Path.Combine(Directory.GetCurrentDirectory(), "content")),  
  11.         RequestPath = new PathString("/outside-content")  
  12.     });  
  13.   
  14.     app.Run(async (context) =>  
  15.     {  
  16.         await context.Response.WriteAsync("Hello Static Files");  
  17.     });  
  18. }  

Add static content to www root and a custom content folder.

static-files-explorer

Access the files using site address.

  • http://[site-address]/hello.html
  • http://[site-address]/outside-content/info.html

Discussion

Static files are served by default from the wwwroot folder and can be accessed as if the content exists in your root folder. The default folder can be changed via WebHostBuilder in Program.cs using following code.

  1. UseWebRoot("public"// changed wwwroot to public  

Static files can also be served from folders outside wwwroot by passing in StaticFileOptions to middleware and setting a FileProvider and RequestPath. This is useful when you want authorized access to files e.g. by returning FileResult action result from a secure controller.

Source Code

GitHub