HttpRequestMessage.Content is lost when it is read in a logging DelegatingHandler in ASP.Net Web API

This is by design. In ASP.NET Web API the body content is treated a forward-only stream that can only be read once.

You might try utilising ASP.NET Web API Tracing but I haven't test it with POST request yet so I'm not sure how/if it is tracing the request body (it is tracing parameters for GET request for sure). You can read more here:

  • Tracing in ASP.NET Web API (Ron Cain)
  • ASP.NET Web API Tracing Preview (Ron Cain)
  • Tracing in ASP.NET Web API (Mike Wasson)

ReadAsStreamAsync method returns the body content.

var body = string.Empty;
using (var reader = new StreamReader(request.Content.ReadAsStreamAsync().Result))
{
    reader.BaseStream.Seek(0, SeekOrigin.Begin);
    body = reader.ReadToEnd();
}

Here's what I ended up doing:

public string SafelyReadContent(HttpRequestMessage request)
{
    var stream = request.Content.ReadAsStreamAsync().Result;
    var reader = new StreamReader(stream);
    var result = reader.ReadToEnd();
    stream.Seek(0, SeekOrigin.Begin);

    return result;
}

@pirimoglu's answer of using a "using" block didn't work for me, since when the reader was disposed, the underlying stream was also closed.