我需要允许各个主机拥有自己的文件夹来提供静态文件。
开始这样做:
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”。
我想找到一个可以动态/在运行时工作的解决方案,所以想知道是否有办法做到这一点?
按照建议,这是使用自定义文件提供程序的第一次尝试。
(如果有更好的写法,请编辑我的或发布新的)
在
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);
}
}