Home > Enterprise >  Can HttpResponseMessage.Content be null?
Can HttpResponseMessage.Content be null?

Time:04-02

Given the expression:

responseBodyJson = await responseMsg.Content.ReadAsStringAsync();

Knowing that responseMsg is an HttpResponseMessage object and is not null, can Content (HttpContent object) be null, in other words, can this expression throw a NullReferenceException ?

CodePudding user response:

It seems that it will always create a new instance if it is null.

https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs

[AllowNull]
public HttpContent Content
{
    get { return _content ??= new EmptyContent(); }
    set
    {
        CheckDisposed();

        if (NetEventSource.Log.IsEnabled())
        {
            if (value == null)
            {
                NetEventSource.ContentNull(this);
            }
            else
            {
                NetEventSource.Associate(this, value);
            }
        }
        _content = value;
    }
}
  • Related