Null 条件运算符,在某些机器上的行为不符合预期

Null Conditional Operator, not behaving as expected on some machines

我在 WebApi 2 项目的 DelegatingHandler 中有以下代码。

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var content = await request.Content?.ReadAsStringAsync();
        _log.Information("Received {request} with content body: {content}.", request, content);

        // Run the rest of the request pipeline.
        var result = await base.SendAsync(request, cancellationToken);

        var responseContent = await result.Content?.ReadAsStringAsync();
        _log.Information("Returning {result} with content body: {responseContent}.", result, responseContent);

        return result;
    }

在我的机器上,这按预期工作,并且在 301 重定向响应期间(其中 result.content 将为空)我得到 responseContent == null;然而,在同事的机器上,他在这一行收到一个空引用异常。我们都使用 4.5.1 运行时,据我们所知,差异如下:

忍者编辑 - the .NET versions and service packs I have installed as well as the ones he has installed...

它无法工作的机器似乎安装了两个 4.5.1 安全更新 (KB2901126 & KB2931368),但我没有,其中一个会导致此问题吗?我需要检查的编译器或编译器选项是否存在差异?还是我在研究解释更简单的东西?

我不知道这两个机器有什么区别,但是你的代码是错误的:

await result.Content?.ReadAsStringAsync();

它的作用是,当 result.Content 不是 null 时,将调用 ReadAsStringAsync() 并且其结果是 awaited,这是应该的。但是当 result.Contentnull 时,整个子表达式 result.Content?.ReadAsStringAsync()null,这意味着 await 将抛出一个 NullReferenceException.

所以,如果你想防止 result.Content 成为 null,你应该使用老式的 if 或三元运算符。