I'm using .netCore 3.1 to create a RESTful API.
Here I'm trying to modify the response body to filter out some values based on a corporate use case that I have.
My problem is that at first, I figured that the CanRead
value of context.HttpContext.Response.Body
is false, thus it is unreadable, so I searched around and found this question and its answers.
which
basically converts a stream that can't seek to one that can
so I applied the answer with a little modification to fit my use case :
Stream originalBody = context.HttpContext.Response.Body;
try
{
using (var memStream = new MemoryStream())
{
context.HttpContext.Response.Body = memStream;
memStream.Position = 0;
string responseBody = new StreamReader(memStream).ReadToEnd();
memStream.Position = 0;
memStream.CopyTo(originalBody);
string response_body = new StreamReader(originalBody).ReadToEnd();
PagedResponse<List<UserPhoneNumber>> deserialized_body;
deserialized_body = JsonConvert.DeserializeObject<PagedResponse<List<UserPhoneNumber>>>(response_body);
// rest of code logic
}
}
finally
{
context.HttpContext.Response.Body = originalBody;
}
But when debugging, I found out that memStream.Length
is always 0
, and therefore the originalBody
value is an empty string : ""
.
Even though after this is executed , the response is returned successfully, (thanks to the finally
block).
I can't seem to understand why this is happening, is this an outdated method? what am I doing wrong? Thank you in advance.