在 IOwinContext 对象中找不到 Get 方法的结果
Cannot find the result of a Get method inside IOwinContext object
我有一个 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
里面,但我不知道具体在哪里,因为它充满了东西。
实际响应是一个流,您需要这样做才能以原始形式返回响应
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)
{
}
我有一个 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
里面,但我不知道具体在哪里,因为它充满了东西。
实际响应是一个流,您需要这样做才能以原始形式返回响应
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)
{
}