2

我在 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 运行时,据我们所知,差异如下:

  • 我正在使用 VS2015 Enterprise SP2(它可以工作),他正在使用 VS2015 Professional SP2(它不工作)

Ninja Edit -我安装的 .NET 版本和服务包以及他安装的那些......

看起来它不工作的机器安装了两个我没有安装的 4.5.1 安全更新(KB2901126KB2931368),其中一个会导致这个问题吗?我需要检查的编译器或编译器选项是否存在差异?还是我在寻找一些解释更简单的东西?

4

1 回答 1

3

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

await result.Content?.ReadAsStringAsync();

它的作用是调用when result.Contentis not并且它的结果是ed ,因为它应该。但是当是时,整个子表达式是,这意味着将抛出一个。nullReadAsStringAsync()awaitresult.Contentnullresult.Content?.ReadAsStringAsync()nullawaitNullReferenceException

因此,如果您想防止result.Content存在null,您可能应该使用老式if或三元运算符。

于 2016-05-14T00:49:49.847 回答