Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read POST Request body in Web API 2

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.

like image 650
Swanand Pangam Avatar asked May 20 '18 07:05

Swanand Pangam


3 Answers

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.

like image 72
user1672994 Avatar answered Sep 24 '22 20:09

user1672994


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.

like image 37
PSK Avatar answered Sep 26 '22 20:09

PSK


  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();

like image 37
waqar iftikhar Avatar answered Sep 25 '22 20:09

waqar iftikhar