使用StaticFiles,根据主机动态设置文件夹

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

我需要允许各个主机拥有自己的文件夹来提供静态文件。

开始这样做:

var hosts = cfg.GetSection("AppSettings:AvailableHosts").Get<string[]>();

foreach (var host in hosts)
{
    app.UseWhen(ctx => ctx.Request.Host.Host == host, appBuilder =>
    {
        appBuilder.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
                Path.Combine(builder.Environment.ContentRootPath, host, "res")),
            RequestPath = "/res"
        });
    });
}

这样做的缺点是,我需要一直更新“appsettings.json”。

我想找到一个可以动态/在运行时工作的解决方案,所以想知道是否有办法做到这一点?

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

按照建议,这是使用自定义文件提供程序的第一次尝试。

(如果有更好的写法,请编辑我的或发布新的)

program.cs

app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/res", StringComparison.OrdinalIgnoreCase), appBuilder =>
{    
    appBuilder.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new HostResFileProvider(appBuilder.ApplicationServices.GetRequiredService<IHttpContextAccessor>(), builder.Environment),
        RequestPath = "/res"
    });
});

还有

IFileProvider

public class HostResFileProvider : IFileProvider
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IWebHostEnvironment _env;

    public HostResFileProvider(IHttpContextAccessor httpContextAccessor, IWebHostEnvironment env)
    {
        _httpContextAccessor = httpContextAccessor;
        _env = env;
    }

    public IDirectoryContents GetDirectoryContents(string subpath)
    {
        return _env.WebRootFileProvider.GetDirectoryContents(subpath);
    }


    public IFileInfo GetFileInfo(string subpath)
    {
        string host = _httpContextAccessor.HttpContext.Request.Host.Host;

        if (!string.IsNullOrWhiteSpace(host))
        {    
            return _env.ContentRootFileProvider.GetFileInfo(Path.Combine(host, subpath));;
        }

        return _env.WebRootFileProvider.GetFileInfo(subpath);
    }


    public IChangeToken Watch(string filter)
    {
        return _env.WebRootFileProvider.Watch(filter);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.