我有一个自我托管的应用程序,它使用OWIN提供一个基本的web服务器。配置的关键部分是以下一行:
appBuilder.UseFileServer(new FileServerOptions {
FileSystem = new PhysicalFileSystem(filePath)
});这提供了filePath中列出的用于浏览的静态文件,而这一点正如愿以偿。
但是,我遇到了这样一种情况,即我希望根据请求逐个请求稍微修改其中一个文件。特别是,我希望从文件系统加载文件的“正常”版本,根据传入的web请求的头稍微修改它,然后将修改后的版本返回给客户端,而不是原始版本。所有其他文件应保持未修改。
我该怎么做呢?
发布于 2015-05-29 02:17:22
嗯,我不知道这是否是一种好的方法,但它似乎是有效的:
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
}
}将其添加到静态文件中间件之前的管道中。
https://stackoverflow.com/questions/30495582
复制相似问题