英文:
getting static code analysis tool error "Calling a method on null object base.Request "
问题
Coverity静态代码分析工具报告了“调用空对象base.Request的方法”错误 (var cid = Request.Headers["CId"];
),针对以下简单的.NET 6 Web API控制器API,
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public string Get()
{
var cid = Request.Headers["CId"];
return cid.ToString();
}
}
这意味着"Request"对象可能为空。
-
我尝试使用null-forgiving运算符!来避免这个问题
var cid = Request!.Headers["CId"];
,但它显示相同的错误。 -
也尝试了对Request进行空检查,尽管它一直显示为真
if (Request != null) { var cid = Request.Headers["CId"]; }
,但依然报同样的错误。
我知道在这种情况下我可以忽略这个错误,因为我知道Request
在我的情况下永远不会为空。
但我仍然想知道是否有解决方法?
英文:
The static code analysis tool "Coverity" complains "Calling a method on null object base.Request" error (var cid = Request.Headers["CId"];
) for below simple .NET 6 Web API controller API,
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public string Get()
{
var cid = Request.Headers["CId"];
return cid.ToString();
}
}
This means that "Request" object can be null.
-
I tried to avoid this using null-forgiving operator !
var cid = Request!.Headers["CId"];
, it's saying same error. -
Also tried null check for Request though it's saying always true
if (Request != null) { var cid = Request.Headers["CId"]; }
, even same error.
I know this I can ignore here as I know Request
can never be null
for my case.
Still wanted to know do we have any solution for it?
答案1
得分: 1
这个问题似乎是因为 object.ToString
返回 string?
。这里没有可能为 null 的情况 ControllerBase.Request
不可为 null,HttpRequest.Headers
也不可为 null(尽管 HttpRequest
有标记为可为 null 引用类型的属性,如 ContentType
)。IHeaderDictionary.Item[String]
也返回非可为 null 的 StringValues
:
> 存储的值,或者如果键不存在则为 StringValues.Empty
。
尝试:
return cid.ToString()!;
或
var cid = Request?.Headers["CId"];
return cid?.ToString()!;
英文:
The issue seems to come from object.ToString
returning string?
. There is nothing what can be null here ControllerBase.Request
is not nullable, HttpRequest.Headers
is not nullable also, (though HttpRequest
has properties marked as nullable reference types like ContentType
). IHeaderDictionary.Item[String]
also returns non-nullable StringValues
:
> The stored value, or StringValues.Empty
if the key is not present.
Try:
return cid.ToString()!;
Or
var cid = Request?.Headers["CId"];
return cid?.ToString()!;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论