首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据请求修改OWIN/Katana PhysicalFileSystem页面

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

Stack Overflow用户
提问于 2015-05-28 01:06:39
回答 1查看 364关注 0票数 2

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

代码语言:javascript
复制
appBuilder.UseFileServer(new FileServerOptions {
    FileSystem = new PhysicalFileSystem(filePath)
});

这提供了filePath中列出的用于浏览的静态文件,而这一点正如愿以偿。

但是,我遇到了这样一种情况,即我希望根据请求逐个请求稍微修改其中一个文件。特别是,我希望从文件系统加载文件的“正常”版本,根据传入的web请求的头稍微修改它,然后将修改后的版本返回给客户端,而不是原始版本。所有其他文件应保持未修改。

我该怎么做呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-29 02:17:22

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

代码语言:javascript
复制
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
    }
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30495582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档