简体   繁体   English

从 OWIN 中间件更改响应对象

[英]Changing the response object from OWIN Middleware

My OWIN middleware is like this.我的OWIN中间件是这样的。 (Framework is ASP.NET Web API). (框架是 ASP.NET Web API)。

public class MyMiddleware : OwinMiddleware
{
    public MyMiddleware(OwinMiddleware next) : base(next) { }

    public override async Task Invoke(OwinRequest request, OwinResponse response)
    {
        var header = request.GetHeader("X-Whatever-Header");

        await Next.Invoke(request, response);

        response.SetHeader("X-MyResponse-Header", "Some Value");
        response.StatusCode = 403;

    }
}

Questions:问题:

  1. Is it the recommended practice to derive from OwinMiddleware ?OwinMiddleware派生是推荐的做法吗? I see that in Katana source, some of the middleware classes derive from OwinMiddleware and some do not.我看到在 Katana 源代码中,一些中间件类派生自OwinMiddlewareOwinMiddleware一些则不是。

  2. I can see the request headers okay.我可以看到请求标头没问题。 Setting response header or status code after Next.Invoke in my middleware has no effect on the response returned to the client.在我的中间件中的Next.Invoke之后设置响应头或状态码对返回给客户端的响应没有影响。 But if I set the response header or status before the Next.Invoke call, the response with headers and the status that I set is returned to the client.但是,如果我在Next.Invoke调用之前设置响应标头或状态,则带有标头和我设置的状态的响应将返回给客户端。 What is the right way of setting these?设置这些的正确方法是什么?

  1. Yes, deriving from OwinMiddleware is recommended.是的,建议从 OwinMiddleware 派生。 The reason some middleware classes don't derive from OwinMiddleware is that either they haven't switched over yet because the class was introduced recently.一些中间件类没有从 OwinMiddleware 派生的原因是它们还没有切换,因为该类是最近引入的。 Or to avoid having the assembly take a dependency on the Microsoft.Owin assembly for some reason.或者为了避免由于某种原因使程序集依赖于 Microsoft.Owin 程序集。

  2. The probable reason setting stuff on the response after calling Invoke on Next doesn't work is that the response HTTP header gets sent as soon as anyone starts writing to the response body stream.在调用 Invoke on Next 后在响应上设置内容不起作用的可能原因是,只要有人开始写入响应正文流,就会发送响应 HTTP 标头。 So any changes to status code or HTTP headers after a middleware component starts writing to the response body won't have any effect.因此,在中间件组件开始写入响应正文后,对状态代码或 HTTP 标头的任何更改都不会产生任何影响。

What you can try doing is to use the OnSendingHeaders callback that OWIN provides.您可以尝试做的是使用 OWIN 提供的 OnSendingHeaders 回调。 Here's how you can use it:使用方法如下:

public override async Task Invoke(IOwinContext context)
{
   var response = context.Response;
   var request =  context.Request;

   response.OnSendingHeaders(state =>
   {
       var resp = (OwinResponse)state;
       resp.Headers.Add("X-MyResponse-Header", "Some Value");
       resp.StatusCode = 403;
       resp.ReasonPhrase = "Forbidden";
    }, response);

  var header = request.Headers["X-Whatever-Header"];

  await Next.Invoke(context);
}

Credit to biscuit314 for updating my answer.感谢 biscuit314 更新我的答案。

I tried to edit Youssef's excellent answer to correct a minor bug and update the example with how the OwinMiddleware now works.我尝试编辑 Youssef 的优秀答案以纠正一个小错误,并使用 OwinMiddleware 现在的工作方式更新示例。

The edit was rejected (well, approved by one, rejected by one for being too minor, and rejected by two for being too major).编辑被拒绝了(嗯,一个人批准,一个人因为太小而被拒绝,两个人因为太重要而被拒绝)。

Here is that version of Youssef's code:这是 Youssef 代码的那个版本:

public override async Task Invoke(IOwinContext context)
{
  var response = context.Response;
  var request =  context.Request;

  response.OnSendingHeaders(state =>
    {
        var resp = (OwinResponse)state;
        resp.Headers.Add("X-MyResponse-Header", "Some Value");
        resp.StatusCode = 403;
        resp.ReasonPhrase = "Forbidden"; // if you're going to change the status code
                                         // you probably should also change the reason phrase
    }, response);

  var header = request.Headers["X-Whatever-Header"];

  await Next.Invoke(context);
}

I used this code to get the time taken by every request.我使用此代码来获取每个请求所花费的时间。

appBuilder.Use(async (context, next) =>
        {
            var watch = new Stopwatch();
            watch.Start();
            await next();
            watch.Stop();
            context.Response.Headers.Set("ResponseTime", watch.Elapsed.Seconds.ToString());
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM