ASP .NET 5 Preview: Serving Static Files

One of the most basic features of just about any non-trivial web application is that of serving static files. Typically, a browser will request all kinds of files: HTML documents, JavaScript files, images, etc.

In ASP .NET 5, the root of the website is (by default) a folder called wwwroot. Any files to be served by the web application should be placed within this folder. However, the ability to serve static files doesn’t come out of the box. To support static files, you need to add the Microsoft.AspNet.StaticFiles NuGet package to your project.json:

If you go to the root of the URL, though, you’ll notice that your index.html doesn’t get retrieved unless you request it explicitly:

That “Hello World” is coming from the end of the pipeline we defined in Configure(), because UseStaticFiles() doesn’t know what to return if we don’t specify a file that exists. We can sort this out by calling UseDefaultFiles():

Our root still serves the default index.html, but when navigating to the images folder, we are presented with a directory listing:

You can also achieve what we have done so far using the UseFileServer() method. Refer to the official documentation on static files to learn how to use UseFileServer(), and for additional configuration options provided by the features we have seen so far.