Static files are stored within the project's web root directory.
The default directory is {content root}/wwwroot,
but is can be changed with the UseWebRoot method.
The parameterless UseStaticFiles method overload marks the files in web root as servable.
app.UseStaticFiles();
The following markup references wwwroot/images/image.png.
<img src="~/images/image.png" class="img" alt="test image" />
the tilde character ~/ points to the web root.
Serve files outside of web root
A request can access the MyStaticFiles/images/image.png file by configuring the Static File Middleware as follows:
using System.IO; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.FileProviders; : builder.Services.AddDirectoryBrowser(); var app = builder.Build(); : app.UseHttpsRedirection(); app.UseStaticFiles(); var fileProvider = new PhysicalFileProvider( Path.Combine(app.Environment.ContentRootPath, "MyStaticFiles")); app.UseStaticFiles(new StaticFileOptions { FileProvider = fileProvider, RequestPath = "/StaticFiles", OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append( "Cache-Control", "no-store"); } }); app.UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = fileProvider, RequestPath = "/DB" }); app.UseAuthorization(); :
The following markup references MyStaticFiles/images/image.png:
<img src="~/StaticFiles/images/image.png" class="img" alt="outside image" />
Uses FileServer Middleware
using System.IO; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.FileProviders; : app.UseHttpsRedirection(); app.UseStaticFiles(); var fileProvider = new PhysicalFileProvider( Path.Combine(app.Environment.ContentRootPath, "MyStaticFiles")); app.UseFileServer(new FileServerOptions { FileProvider = fileProvider, RequestPath = "/StaticFiles", EnableDirectoryBrowsing = true }); app.UseAuthorization(); :
'Web > ASP.NET Core' 카테고리의 다른 글
IHttpClientFactory (0) | 2023.10.24 |
---|