ASP.NET Core教程-Configuration(配置)-预定义中间件-静态文件支持
更新记录
转载请注明出处:
2022年11月15日 发布。
2022年11月12日 从笔记迁移到博客。
基本使用
使用 UseStaticFiles() 中间件即可支持静态文件,然后将静态文件放在根目录下的wwwroot文件夹下即可。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//引入支持静态文件中间件
app.UseStaticFiles();
}
所在命名空间
using Microsoft.Extensions.FileProviders;
支持的配置属性
UseStaticFiles() 中间件支持使用 StaticFileOptions 类型做为静态文件中间的配置项。支持如下参数:
名称 | 描述 |
---|---|
ContentTypeProvider | This property is used to get or set the IContentTypeProvider object that is responsible for producing the MIME type for a file. The default implementation of the interface uses the file extension to determine the content type and supports the most common file types. |
DefaultContentType | This property is used to set the default content type if the IContentTypeProvider cannot determine the type of the file. |
FileProvider | This property is used to locate the content for requests, as shown below. |
OnPrepareResponse | This property can be used to register an action that will be invoked before the static content response is generated. |
RequestPath | This property is used to specify the URL path that the middleware will respond to, as shown below. |
ServeUnknownFileTypes | By default, the static content middleware will not serve files whose content type cannot be determined by the IContentTypeProvider. This behavior is changed by setting this property to true. |
额外增加静态文件夹
除了默认的 wwwroot 还可以添加额外的静态文件存放的文件夹。使用 FileProvider 属性即可。
app.UseStaticFiles(
new StaticFileOptions()
{
//指定静态文件夹的物理路径
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"StuffOnDisk")),
//URL请求时对应的路径
RequestPath = new PathString("/StaticFiles")
}
);
额外的子路径文件夹
配置应用
app.UseStaticFiles(
new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),@"wwwroot", "assets")),
RequestPath = new PathString("/assets")
}
);
app.UseDirectoryBrowser(
new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),@"wwwroot", "assets")),
RequestPath = new PathString("/assets")
}
);
容器中注入:
services.AddDirectoryBrowser();
增加非标准内容类型
请求的文件含未知内容类型时,设置默认以图像形式返回请求
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true, DefaultContentType = "image/png"
});
还可以按需要 进行配置 单独文件类型如下
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".image"] = "image/png";
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()),
ContentTypeProvider = provider
});
本文来自博客园,作者:重庆熊猫,转载请注明原文链接:https://www.cnblogs.com/cqpanda/p/16882678.html