UseStaticFiles
In an ASP.NET Core Web Application, we can support static
files, like PNG, JPG, JS, or CSS files. We must call the UseStaticFiles
method.
Please create an ASP.NET Core Web Application in Visual Studio. Then open the Startup class
, and locate the Configure
method—this is where we can call UseStaticFiles
.
Add a folder to the Web Application project called wwwroot—this is a special folder that is used to serve static
files. Then add a PNG or other file to it.
UseStaticFiles()
in the Configure
method—this is needed to enable static
file serving.MapGet
.using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; namespace WebApplication3 { public class Startup { const string _html = "<html><body><img src=hello-world.png></body></html>"; public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); // Add a wwwroot folder to the WebApplication project in Visual Studio. // ...Then drag an image to wwwroot. app.UseStaticFiles(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync(_html); }); }); } } }
UseStaticFiles
There are several overloads of UseStaticFiles
, but in my experience the call with no arguments tends to be effective for most cases.
You can add directories to the wwwroot folder—for larger web applications, it is often useful to have a JS or CSS directory. An "Images" directory is also common.
With an ASP.NET Core Web Application, we can enable serving static
files like images or JavaScript by calling UseStaticFiles
. We must add a wwwroot directory to store the files.