Asp.Net Core静态文件包含/排除规则



我已经设置了静态文件和目录浏览:

PhysicalFileProvider physicalFileProvider = new PhysicalFileProvider(somePath, ExclusionFilters.None);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = physicalFileProvider,
RequestPath = "/files",
ServeUnknownFileTypes = true
}); 
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = new PhysicalFileProvider(somePath),
RequestPath = "/files"
});

我一直在搜索文档和浏览对象模型,但我不知道如何设置包含和排除过滤器。我目前的代码是过滤文件开始与.(隐藏?但我在Windows上运行)我想显示和下载这些文件,但隐藏其他类型,如*。Json和web.config.

这是一个有点hack,但它为我工作。你可以创建一个新的文件提供程序,在底层使用PhysicalFileProvider(或其他任何东西),但根据模式隐藏文件。

public class TplFileProvider : IFileProvider
{
private readonly IFileProvider fileProvider;
public TplFileProvider(string root)
{
fileProvider = new PhysicalFileProvider(root);
}
public TplFileProvider(string root, ExclusionFilters exclusionFilter)
{
fileProvider = new PhysicalFileProvider(root, exclusionFilter);
}
public IDirectoryContents GetDirectoryContents(string subpath)
{
return (IDirectoryContents) fileProvider.GetDirectoryContents(subpath).Where(i => isAllowed(i.Name));
}
public IFileInfo GetFileInfo(string subpath)
{
var file = fileProvider.GetFileInfo(subpath);
if (isAllowed(subpath))
{
return file;
}
else
{
return new NotFoundFileInfo(file.Name);
}
}
private static bool isAllowed(string subpath)
{
return subpath.EndsWith(".json") || subpath.Equals("web.config");
}
}

最新更新