我如何要求Owin/Katana写头输出流

本文关键字:Katana 输出流 Owin | 更新日期: 2023-09-27 18:12:28

当我写入响应时,Katana跳过发送Elapsed-Time响应头。在我第一次写入流之前,我怎么能让它为我设置头呢?

中间件# 1

    public override async Task Invoke(IOwinContext context)
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        await Next.Invoke(context);
        stopwatch.Stop();
        context.Response.Headers.Add("Elapsed-Time", new[] {stopwatch.ElapsedMilliseconds.ToString()});
    }
中间件# 2

    public override async Task Invoke(IOwinContext context)
    {
        await context.Response.WriteAsync("test");
    }

我如何要求Owin/Katana写头输出流

经过一些研究,答案是设置头需要从OnSendingHeaders中发生。这确保了在写入输出流之前设置报头。例如:

    public override async Task Invoke(IOwinContext context)
    {
        var stopwatch = new Stopwatch();
        context.Response.OnSendingHeaders(x =>
        {
            stopwatch.Stop();
            context.Response.Headers.Add("X-Processing-Time", new[] {stopwatch.ElapsedMilliseconds.ToString()});
        }, null);
        stopwatch.Start();
        await Next.Invoke(context);
        stopwatch.Stop();
    }

使用ResponseHeaders属性

public override async Task Invoke(IOwinContext context)
{
    context.Response.Headers.Add("Content-Length", <somelength>);
    await context.Response.WriteAsync("test");
}

你的中间件看起来正确。也许,您在配置中有问题。

检查,如果你已经像这样流水线了你的中间件:

app.Use(typeof(MiddlewareOne))
   .Use(typeof(MiddlewareTwo));

顺便说一下,您不需要两个中间件。这将作为wall:

public class MyMiddleware : OwinMiddleware
{
    public MyMiddleware(OwinMiddleware next)
        : base(next)
    {}
    public override async Task Invoke(IOwinContext context)
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        await context.Response.WriteAsync("test");
        stopwatch.Stop();
        context.Response.Headers.Add("Elapsed-Time", new[] {stopwatch.ElapsedMilliseconds.ToString()});
    }
}

,配置为:

app.Use(typeof(MyMiddleware));