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

问题描述 投票:0回答:1

我已经设置了静态文件和目录浏览,如下所示:

    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。

c# asp.net-core .net-core static-files
1个回答
2
投票

这有点麻烦,但对我有用。您可以创建一个新的文件提供程序,该文件提供程序在幕后使用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");
    }
}

编辑:这是使用文件类型白名单的更好方法:

var path = Path.GetFullPath(rawPath);

var mapping = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        { ".json", "application/json" },
        { ".jpg", "image/jpeg" },
        { ".png", "image/png" },
    };
staticFileOptions = new StaticFileOptions()
{
    RequestPath = "/StaticTiles",
    ServeUnknownFileTypes = false,
    ContentTypeProvider = new FileExtensionContentTypeProvider(mapping),
    FileProvider = new PhysicalFileProvider(path),
};
app.UseStaticFiles(staticFileOptions);
© www.soinside.com 2019 - 2024. All rights reserved.