I want to log information about HttpRequestMessage responses in a Visual C# Web API program. I want to use a message handler (inheriting from DelegatingHandler) like this:
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// log request.Method & request.RequestUri
var result = await base.SendAsync(request, cancellationToken);
// log first 100 chars of result.Content
return result
}
The issue is that result.Content
will sometimes be huge, so I want to limit it to only printing the first N characters (roughly 50).
What I tried:
- Copying the whole thing to a string with
toString()
and usingSubString
. This does exactly what I want but it seems wasteful to read huge strings into memory and then only use the first few characters - I feel like there must be a better way. - Various solutions from around the internet that read the chars but remove them from the stream. I need to send the full stream back as is.