根据请求修改OWIN/Katana PhysicalFileSystem页面



我有一个自托管的应用程序,使用OWIN提供一个基本的web服务器。配置的关键部分如下行:

appBuilder.UseFileServer(new FileServerOptions {
    FileSystem = new PhysicalFileSystem(filePath)
});

这提供了filePath中列出的用于浏览的静态文件,这部分工作如预期的那样。

然而,我遇到了一种情况,我想在每个请求的基础上稍微修改其中一个文件。特别是,我想从文件系统中加载文件的"正常"版本,根据传入的web请求的头稍微修改它,然后将修改后的版本返回给客户端,而不是原始版本。

我该怎么做呢?

嗯,我不知道这是否是一个好的方法来做到这一点,但它似乎工作:

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
    }
}

将其添加到静态文件中间件之前的管道中

最新更新