[.NET Core 2.1] Using a single stream in two different middlewares
Hi, I am working on a Core 2.1 webAPI project. I have two different middlewares. Both the middlewares use HttpContext to do their work. The first middleware logs the request and response for each call (I know there are already made solutions for this, this is just for practice), the second middleware generates a file and writes the contents of the response to that file. So both these middlewares make use of HttpContext. The code for both middlewares is almost identical because they both read the stream. This is the code for the 1st one:
public async Task Invoke(HttpContext context) { var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { context.Response.Body = responseBody; await _next(context); string responseBodyAsString = await FormatResponse(context.Response); if (context.Response.StatusCode != 204) { await responseBody.CopyToAsync(originalBodyStream); } . . . . . . . } }
And the second one:
public async Task Invoke(HttpContext context) { var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { string requestBodyAsString = await FormatRequest(context.Request); context.Response.Body = responseBody; await _next(context); string responseBodyAsString = await FormatResponse(context.Response); if (context.Response.StatusCode != 204) { WriteToFile(requestBodyAsString + "\n" + responseBodyAsString); ......... } } }
The problem is that when I use them both together, I get:
System.ObjectDisposedException: Cannot access a closed Stream. at System.IO.MemoryStream.Seek(Int64 offset, SeekOrigin loc)
in the first middleware. I tried to debug the problem and this is the flow:
Call made --> Other middleware --> Middleware1 --> Middleware2 --> MiddlewareN --> Middleware2 --> Middleware1 --> Exception
So it happens when we come back to the first middleware. I think this is because we open the stream in Middleware1 -> Invoke Middleware2 --> Middleware2 closes the stream --> we come back to Middleware1 and try to read it. Is this correct? If it is, what can I do to fix this?
0 comments:
Post a Comment