I have an OwinMiddleware
with an Invoke
method looking kind of like this:
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?
...
}
The Invoke
method invokes a Get
method, located inside a controller, which looks kind of like this:
[HttpGet]
public IHttpActionResult Get(some params...)
{
...
return "myvalue";
...
}
After the execution of the Get
method, the program goes back to the Invoke
method of my middleware. I think that the response of the Get
method, namely myvalue
, should be contained inside context.Response
, but I don't know where precisely, because it's full of things.
Actualy response is a stream and You need to do this to get response back in orignal form
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)
{
}