Web applications are typically dynamic (frequently changing) in nature. However some of the files associated with web applications do not change. For example, if a file contains code that does not need to be modified we would consider it to be static; the same is true for images that we want displayed. Files that can be presented to the application as-is, without any processing, are known as static files. Some examples of static files would be CSS, Bootstrap, JQuery, and images. Some of these files (Bootstrap, JQuery, etc) are provided by default in the ASP.NET templates.
Static files make up an important part of the application because sometimes they contain code that controls how the application looks and/or behaves. If we want our site to use static files we have to explicitly declare that we want the files to be made available and fortunately, there’s a built-in middleware component for that.
The UseStaticFiles()
method is available to ensure static file content is rendered alongside the HTML for our web applications. Static files are stored in the wwwroot directory and are accessible via a path relative to the web root. In the below example, the wwwroot directory contains css, js, lib directories and the favicon.ico image file.
RazorApp ├── Program.cs ├── RazorApp.csproj ├── Startup.cs ├── ... └── wwwroot ├── css │ └── site.css ├── favicon.ico ├── js │ └── site.js └── lib ├── bootstrap │ └── ... ├── jquery │ └── ... ├── jquery-validation │ └── ... └── jquery-validation-unobtrusive └── ...
For reference, the site.js file would be available at:
http://localhost:5000/js/site.js
Instructions
The UseStaticFiles
middleware component helps the site render CSS, which affects the site’s styling. Examine the site without the UseStaticFiles
component.
Within the Configure()
method, right after the line app.UseHttpsRedirection()
, add the line app.UseStaticFiles()
.