From the course: Learning ASP.NET Core MVC

Serving static files

From the course: Learning ASP.NET Core MVC

Start my 1-month free trial

Serving static files

- [Instructor] Now that I've described how asp.net core uses middleware to process requests, I'll show you how to add the middleware that can respond to requests with static content, such as HTML pages and CSS. In order to enable my site to serve these static files, I'll simply replace the two app calls in the configure method of my startup class from before with the following line, app.UseFileServer. This middleware will take a look at the URL of any request made to the site and try to map it to a file at the same path in the www root folder of my project, which is a special folder that helps separate the static content that we'd like to expose to the world from the rest of our applications code, which we'd rather not share. If that folder doesn't exist in your project, go ahead and create it now. Then I'll add to this folder any static content that I want my application to serve. For a good example, take a look at the artifacts folder in chapter one of your exercise files and open up the site folder. This folder contains all of the static HTML and CSS for the Explore California site that I showed earlier, so I'll simply copy all these files and paste them into the new www root folder in my project and that's all I need to do. With this static content in the right place and the call to app.UseFileServer to register that static files middleware component, which tells asp.net core to try to map any unhandled request to a file in this folder, I can now run my site and see my Explore California mock up, which means that my application is serving these static files properly. If you're wondering why I'm seeing this page when hitting the root URL of my site, it's because the UseFileServer middleware even includes a setting, which maps the root of a folder to a default file, in this case, index.html. As I've shown here, the file server middleware is a powerful feature that lets you render any kind of static content that you'd like.

Contents