HttpResponseMessage.Content 可以为空吗?

ana*_*ciu 4 c# http httpresponse .net-core .net-core-3.1

给出表达式:

responseBodyJson = await responseMsg.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

知道responseMsg是一个HttpResponseMessage对象并且不为 null,那么Content( HttpContentobject) 是否可以为 null,换句话说,这个表达式可以抛出一个 吗NullReferenceException

小智 7

如果它为空,它似乎总是会创建一个新实例。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)