我有一个使用 OWIN 提供基本 Web 服务器的自托管应用程序。配置的关键部分是以下行:
appBuilder.UseFileServer(new FileServerOptions {
FileSystem = new PhysicalFileSystem(filePath)
});
这提供了用于浏览的 filePath
中列出的静态文件,这一切都按预期工作。
但是,我遇到过这样一种情况,我想根据请求逐个修改其中一个文件。特别是,我想从文件系统加载文件的“正常”版本,根据传入的 Web 请求的 header 对其进行轻微更改,然后将更改后的版本而不是原始版本返回给客户端。所有其他文件应保持不变。
我该怎么做?
最佳答案
好吧,我不知道这是否是一个好的方法,但它似乎有效:
internal class FileReplacementMiddleware : OwinMiddleware
{
public FileReplacementMiddleware(OwinMiddleware next) : base(next) {}
public override async Task Invoke(IOwinContext context)
{
MemoryStream memStream = null;
Stream httpStream = null;
if (ShouldAmendResponse(context))
{
memStream = new MemoryStream();
httpStream = context.Response.Body;
context.Response.Body = memStream;
}
await Next.Invoke(context);
if (memStream != null)
{
var content = await ReadStreamAsync(memStream);
if (context.Response.StatusCode == 200)
{
content = AmendContent(context, content);
}
var contentBytes = Encoding.UTF8.GetBytes(content);
context.Response.Body = httpStream;
context.Response.ETag = null;
context.Response.ContentLength = contentBytes.Length;
await context.Response.WriteAsync(contentBytes, context.Request.CallCancelled);
}
}
private static async Task<string> ReadStreamAsync(MemoryStream stream)
{
stream.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
return await reader.ReadToEndAsync();
}
}
private bool ShouldAmendResponse(IOwinContext context)
{
// logic
}
private string AmendContent(IOwinContext context, string content)
{
// logic
}
}
将其添加到管道中静态文件中间件之前的某处。
关于c# - 根据要求修改 OWIN/Katana PhysicalFileSystem 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30495582/