如何在交付前更改物理文件提供商中的静态文件?

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

我有不同的 ASP.NET Core(非 MVC)应用程序,它们为多个静态 Angular 应用程序提供服务。

我使用PhysicalFileProvider类这样做,效果很好。

// This works fine!
var fileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "NG", "UI", "Login"));
var options = new FileServerOptions
{
    FileProvider = fileProvider,
    RequestPath = "/ng/ui/login",
    EnableDirectoryBrowsing = true
};

但是,在将这些静态文件交付给客户端之前,我需要更改 RAM 中的一些文件,而不是在磁盘上物理更改它们。

我已经编写了自己的物理文件提供程序的实现,但我不明白在哪个时间点或在哪里实际从磁盘读取文件。

PhysicalFileProvider 基本上只有两到三个函数,它们似乎只提供有关文件的信息,而不是实际的文件字节。

// These two functions of PhysicalFileProvider only deliver informations, but not the files? Am I wrong? IDirectoryContents GetDirectoryContents(string subpath) IFileInfo GetFileInfo(string subpath)

我的问题是: 需要在 ASP.NET 服务管道中挂钩什么样的中间件,才能在交付之前更改 RAM 中的静态文件(假设是一个简单的文本文件)?

感谢您的任何提示!

c# asp.net-core middleware static-files fileprovider
1个回答
0
投票
就我个人而言,我会选择通过“普通”操作或可能是一些中间件来提供文件的方法,但如果您想尝试使用文件提供程序解决此问题,那么您需要使用两个接口

IFileProvider

IFileInfo

class MyFileProvider : IFileProvider { private readonly string _root; private readonly PhysicalFileProvider _provider; public MyFileProvider(string root) { _root = root; _provider = new PhysicalFileProvider(_root); } public IDirectoryContents GetDirectoryContents(string subpath) => _provider.GetDirectoryContents(subpath); public IFileInfo GetFileInfo(string subpath) { var fileInfo = _provider.GetFileInfo(subpath); return new MyFileInfo(fileInfo); } public IChangeToken Watch(string filter) { throw new NotImplementedException(); } } class MyFileInfo : IFileInfo { private static readonly ReadOnlyMemory<byte> ToAppend = new(" Hello World!"u8.ToArray()); private readonly IFileInfo _fileInfo; public MyFileInfo(IFileInfo fileInfo) => _fileInfo = fileInfo; public Stream CreateReadStream() { var readStream = _fileInfo.CreateReadStream(); var memoryStream = new MemoryStream(); readStream.CopyTo(memoryStream); memoryStream.Write(ToAppend.Span); memoryStream.Seek(0, SeekOrigin.Begin); return memoryStream; } // disables caching like behavior public DateTimeOffset LastModified => DateTimeOffset.UtcNow; // needed to serve correct length public long Length => _fileInfo.Length + ToAppend.Length; // otherwise will try serving file from disk as is as far as I can see public string? PhysicalPath => null; public bool Exists => _fileInfo.Exists; public bool IsDirectory => _fileInfo.IsDirectory; public string Name => _fileInfo.Name; }
并注册:

var myFileProvider = new MyFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")); app.UseFileServer(new FileServerOptions() { FileProvider = myFileProvider, RequestPath = new PathString("/StaticFiles"), EnableDirectoryBrowsing = true });
这是一个远非完美的示例实现,它将 

" Hello World!"

 附加到所提供的文件中,例如我的文件包含 
Test
:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.