C# – Read POST Request body in Web API 2

asp.net-web-api2c

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.

Best Answer

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.

Related Topic