无法在IOwinContext对象中找到Get方法的结果

时间:2017-07-26 13:09:26

标签: get owin middleware

我的OwinMiddleware Invoke方法看起来像这样:

public override async Task Invoke(IOwinContext context)
{
    ...
    //The next line launches the execution of the Get method of a controller
    await Next.Invoke(context);
    //Now context.Response should contain "myvalue" right?
    ...
}

Invoke方法调用位于控制器内的Get方法,看起来像这样:

[HttpGet]
public IHttpActionResult Get(some params...)
{
    ...
    return "myvalue";
    ...
}

执行Get方法后,程序返回到我的中间件的Invoke方法。我认为Get方法的响应,即myvalue,应该包含在context.Response中,但我不知道究竟在哪里,因为它充满了的东西。

1 个答案:

答案 0 :(得分:0)

Actualy响应是一个流,您需要这样做以获得orignal形式的响应

 try{
      var stream = context.Response.Body;
      var buffer = new MemoryStream();
      context.Response.Body = buffer;
      await _next.Invoke(environment);
      buffer.Seek(0, SeekOrigin.Begin);
      var reader = new StreamReader(buffer);
      // Here you will get you response body like this
      string responseBody = reader.ReadToEndAsync().Result;
      // Then you again need to set the position to 0 for other layers
      context.Response.Body.Position = 0;
      buffer.Seek(0, SeekOrigin.Begin);
      await buffer.CopyToAsync(stream);
    }
    catch(Exception ex)
    {

    }