Static Files 包括 HTML,CSS,图片,JavaScript,以及其他静态资源文件。
即网站本身的内容。
Static Files 保存在项目的 Web Root 目录,即 wwwroot 文件夹中。
而wwwroot目录是Content Root 的子目录, Content Root 还包括其他代码文件,.exe 和 .dll 文件。
wwwroot文件夹的结构如下:
在App启动时调用UseStaticFiles启用静态文件service后,会将wwwroot 目录映射到 https:///
app.UseStaticFiles();
可以通过url https://localhost:5001/images/1.jpg 访问这个图片文件。
如果想将其他目录映射到 https:///otherroot/images/1.jpg,比如
可以这样映射:
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, "otherroot")),
RequestPath = "/otherroot",
OnPrepareResponse = ctx =>
{
var cacheMaxAgeOneWeek = (60 * 60 * 24 * 7).ToString();
ctx.Context.Response.Headers.Append(
"Cache-Control", $"public, max-age={cacheMaxAgeOneWeek}"); //添加过期时间
}
});
然后在html代码中可以这样引用:
<img src="~/otherroot/images/1.png" class="img" asp-append-version="true" alt="Test">
需要满足3个条件:
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
以禁止匿名访问这些文件。
Directory Browsing 服务可以列出某个目录下的所有文件。
可以通过 AddDirectoryBrowser()启用:
builder.Services.AddDirectoryBrowser();
var fileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.WebRootPath, "MyImages"));
var requestPath = "/MyImages";
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = fileProvider,
RequestPath = requestPath
});
使用app.UseDefaultFiles()后,
app.UseDefaultFiles();
会在wwwroot 下依次查找这些文件作为入口
也可以指定文件名mydefault.html:
var options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("mydefault.html");
app.UseDefaultFiles(options);
app.UseFileServer 是 UseStaticFiles,UseDefaultFiles 或者 UseDirectoryBrowser的组合。
builder.Services.AddDirectoryBrowser();
app.UseFileServer(enableDirectoryBrowsing: true);
上面的代码会启用UseStaticFiles,UseDefaultFiles,和DirectoryBrowsing。
FileExtensionContentTypeProvider 的 Mappings 属性可以将文件扩展名 映射到 MIME Content Types。
// Set up custom content types - associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4");
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
});