Home
Map
UseStaticFiles ExampleCall the UseStaticFiles method in ASP.NET Core to access files in wwwroot and support image loading.
ASP.NET
This page was last reviewed on May 26, 2023.
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.
Getting started. 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.
Wwwroot, code. 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.
Next Add a call to UseStaticFiles() in the Configure method—this is needed to enable static file serving.
Configure
Then Specify a small HTML page, and write this in the lambda expression inside 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); }); }); } } }
Notes, UseStaticFiles. There are several overloads of UseStaticFiles, but in my experience the call with no arguments tends to be effective for most cases.
Notes, directories. 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.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.