skip to Main Content

We have an api method that can return a null value. It returns its like this:

 var formattedValue= null;
 return Ok(formattedValue);

Then on the client we parse the response like this:

 // Check if it's null
 var result = await httpResponseMessage.Content.ReadAsStringAsync();
 if (result == null)
 {
     return null;
 }

however the ReadAsStringAsync() returns an empty string by default.

I can’t find a way to check if the content is completely empty ie null.

2

Answers


  1. On the client side, you can use the following code to parse the response:

    // Check if it's null
    var result = await httpResponseMessage.Content.ReadAsStringAsync();
    
    if (string.IsNullOrEmpty(result))
    {
        return null;
    }
    

    In this case, ReadAsStringAsync() will return an empty string instead of null. To ensure the content is completely empty, i.e., null, you can use string.IsNullOrEmpty(result) to check.

    Login or Signup to reply.
  2. There are Headers which are associated with the HttpResponseMessage

    • like Allow, Age, RetryAfter, etc.

    There are other Headers which are associated with the HttpContent

    • like Content-Range, Content-Length, Content-Type, etc.

    For more details please check this post.


    Gladly it is quite easy to fetch the Content-Length through the HttpContent:

    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync("https://postman-echo.com/time/now");
    var length = response.Content.Headers.ContentLength; // 29, because the body is not empty
    
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync("https://postman-echo.com/patch");
    var length = response.Content.Headers.ContentLength; // 0, because the body is empty
    

    So, you can branch based on the ContentLength

    if (httpResponseMessage.Content.Headers.ContentLength > 0)
    {
        ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search