我在一个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运行时,据我们所知,差异如下:
Ninja Edit - the .NET versions and service packs I have installed as well as the ones he has installed ...
看起来它不工作的机器安装了两个4.5.1安全更新(KB2901126&amp; KB2931368),我不这样做,其中一个会导致此问题吗?我需要检查编译器或编译器选项是否有区别?或者我正在研究一些更简单的解释?
答案 0 :(得分:3)
我不知道这两台机器之间的区别是什么,但是你的代码错了:
await result.Content?.ReadAsStringAsync();
这是做什么的,当result.Content
不是null
时,ReadAsStringAsync()
被调用,其结果是await
,就像它应该的那样。但是当result.Content
为null
时,整个子表达式result.Content?.ReadAsStringAsync()
为null
,这意味着await
会抛出NullReferenceException
。
因此,如果您想要防止result.Content
null
if
,您应该使用老式的function repeatString(s, count) {
var result = "";
var num = 1;
while ( num++ <= count ) {
result += s;
}
return result;
}
或三元运营商。