c# - 根据要求修改 OWIN/Katana PhysicalFileSystem 页面

标签 c# http owin katana

我有一个使用 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/

相关文章:

c# - 如何使用 IDataErrorInfo 从 ViewModel 强制更新 View 的验证错误?

c# - 如何使用 C# 为 ListView 控件中的项目添加边框?

rest - 如果您发出 PUT 请求并且服务器上没有这样的实体怎么办?

c# - 使用 RedisSessionStateProvider 时出现 Microsoft.Owin.Security.AuthenticationTicket SerializationException

c# - 入口控件扩展到 StackLayout 容器之外

apache - 自定义 URI 方案的类似 HTTP 处理,可能吗?

http - 服务器发送响应缓慢时http超时多久?

c# - OWIN 究竟使用什么函数来生成 token ;可以杠杆吗?

c# - 如何防止 ASP.NET Identity 外部登录在 url 末尾添加#?

c# - 使用 HashSet<int> 创建整数集