Search code examples
c#.nethttpclientdotnet-httpclient

View response body for HttpClient.PostAsync


I a POST in Postman which generates the following Curl:

curl --location --request POST 'https://authqa.cqi.newry.me.com/as/token.oauth2' \
--header 'Authorization: Basic QVBJX0JURUNSRUZEQVRBOlAzNkNEAAE3RVdGUzRPT0NLQlQ0SERaS1pGRTZHTksyQkNJTFVJWT0=' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: PF=mgvtuOC0jyPx3Lbrmw1hTX; BIGipServerauthqa-9031=1948242442.18211.0000' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'charset=utf-8'

It returns the following body:

{
    "access_token": "generated_token",
    "token_type": "Bearer",
    "expires_in": 1799
}

I'm trying to do the equivalent in C# using HttpClient.

This is the where the POST is done:

var body = new StringContent("grant_type=client_credentials", Encoding.UTF8,
                "application/x-www-form-urlencoded");
var httpResponseMessage = await _client.PostAsync("sa/token.oauth2", body);

I get the below with httpResponseMessage.ToString().

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
 {
   Date: Sun, 17 Jan 2021 21:19:39 GMT
   X-Frame-Options: SAMEORIGIN
   Strict-Transport-Security: max-age=31536000
   Content-Security-Policy: frame-ancestors *.cmegroup.com *.chicago.cme.com
   X-XSS-Protection: 1;mode=block
   Cache-Control: no-store, no-cache
   Pragma: no-cache
   Set-Cookie: PF=4sugakrnEHwY5zWIXYasGo;Path=/;Secure;HttpOnly;SameSite=None
   Set-Cookie: BIGipServerauthqa-9031=1897910794.18211.0000; path=/; Httponly; Secure
   Transfer-Encoding: chunked
   Expires: Thu, 01 Jan 1970 00:00:00 GMT
   Content-Type: application/json; charset=utf-8
}

I can't see the response body posted above but I suspect it's the Content: System.Net.Http.HttpConnectionResponseContent. Don't know how to view it though. Can anybody tell me how I view the body as described above?


Solution

  • HttpClientResponse contains content and you can read like this:

    var body = new StringContent("grant_type=client_credentials", Encoding.UTF8,
                    "application/x-www-form-urlencoded");
    var httpResponseMessage = await _client.PostAsync("sa/token.oauth2", body);
    var responseContent = await httpResponseMessage.Content.ReadAsStringAsync(); // here you can read content as string
    ...
    

    Also check here for more info.