我在 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 将为 null),我得到 responseContent == null;然而,在同事的机器上,他在这一行收到空引用异常。我们都使用4.5.1运行时,据我们所知,差异如下:
- 我使用的是 VS2015 Enterprise SP2(可以使用),他使用的是 VS2015 专业 SP2(不起作用的地方)
忍者编辑 - 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()
被调用,其结果是 await
编辑,因为它应该。但是当 result.Content
是 null
,整个子表达式 result.Content?.ReadAsStringAsync()
是 null
,这意味着 await
会抛出 NullReferenceException
.
所以,如果您想防范 result.Content
是null
,你可能应该使用老式的 if
或三元运算符。
关于c# - 空条件运算符,在某些机器上的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218581/