1

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 using SubString. 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.
alksdjg
  • 1,019
  • 2
  • 10
  • 26
  • check this question [Read HttpContent stream until a character limit using StreamReader](https://stackoverflow.com/questions/31015479/read-httpcontent-stream-until-a-character-limit-using-streamreader) – PLopes Apr 07 '20 at 11:40

0 Answers0