【问题标题】:Modify OWIN/Katana PhysicalFileSystem page on request根据要求修改 OWIN/Katana PhysicalFileSystem 页面
【发布时间】:2015-08-10 07:31:16
【问题描述】:

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

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

这提供了filePath 中列出的静态文件以供浏览,并且按预期工作。

但是,我遇到了一种情况,我想根据请求对其中一个文件进行轻微修改。特别是,我想从文件系统加载文件的“正常”版本,根据传入的 Web 请求的标头稍微更改它,然后将更改后的版本而不是原始版本返回给客户端。所有其他文件应保持不变。

我该怎么做?

【问题讨论】:

    标签: c# http owin katana


    【解决方案1】:

    好吧,我不知道这是否是一种好的方法,但它似乎有效:

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

    将此添加到管道中静态文件中间件之前的某处。

    【讨论】:

      猜你喜欢
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      相关资源
      最近更新 更多