4
votes

Just for learning purpose, I am logging all http requests to my Web API 2 application using a handler.

enum LogType {Information = 1, Warning = 2, Error = 3 }
public class LogHandler: DelegatingHandler
{
    async protected override Task SendAsync(HttpRequestMessage httpRequest, CancellationToken cancellationToken)
    {
        Trace.WriteLine(httpRequest.ToString(), LogType.Information.ToString());
        var response = await base.SendAsync(httpRequest, cancellationToken);
        return response;
    }
}

This just prints the Request Headers as follows:

Information: Method: POST, RequestUri: 'http://localhost:49964/school/title?number=1&name=swanand pangam', Version: 1.1, Content: System.Web.Http.WebHost.HttpControllerHandler+LazyStreamContent, Headers:
{
  Cache-Control: no-cache
  Connection: keep-alive
  Accept: text/csv
  Accept-Encoding: gzip
  Accept-Encoding: deflate
  Host: localhost:49964
  User-Agent: PostmanRuntime/7.1.1
  Postman-Token: 074c3aab-3427-4368-be25-439cbabe0654
  Content-Length: 31
  Content-Type: text/plain
}

But I am also sending a json object in POST body which is not printed. I want to print both the Headers as well as body. Also I can't find anything in the 'HttpRequestMessage' object while debugging.

3

3 Answers

7
votes

You should read the content as below

    // log request body
    string requestBody = await httpRequest.Content.ReadAsStringAsync();
    Trace.WriteLine(requestBody);

This will log the request body.

2
votes

You can read the post request like following.

 string requestBody = await request.Content.ReadAsStringAsync();
 var response = await base.SendAsync(httpRequest, cancellationToken);

In case you wan't to log the response also which has been generated, you can try like following.

 var responseBody = await response.Content.ReadAsStringAsync();

Above code will have performance implication in you application as it will hit for each and every operation call, you need to be cautious about this. You may consider a flag to enable and disable this.

2
votes
  var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();