How do I ask Owin/Katana to write headers to the output stream?

流过昼夜 提交于 2020-01-02 04:27:07

问题


When I write to the response, Katana skips sending out the Elapsed-Time response header. How can I have it set the headers for me before I write to the stream for the first time?

Middleware #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()});
    }

Middleware #2

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

回答1:


After some research, the answer is that settings headers needs to happen from within OnSendingHeaders. This ensures that the headers are set before the output stream is written to. For example:

    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();
    }



回答2:


Use Response's Headers property.

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

UPDATE

Your Middlewares looks correct. Perhaps, you have issue in the configuration.

Check, if you have pipelined your middleawres like this:

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

By the way, you haven't necessity of two midlewares. This will work as 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()});
    }
}

and configuration is:

app.Use(typeof(MyMiddleware));


来源:https://stackoverflow.com/questions/32532058/how-do-i-ask-owin-katana-to-write-headers-to-the-output-stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!