“getting static code analysis tool error ‘Calling a method on null object base.Request'”

huangapple go评论64阅读模式
英文:

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"对象可能为空。

  1. 我尝试使用null-forgiving运算符!来避免这个问题 var cid = Request!.Headers["CId"];,但它显示相同的错误。

  2. 也尝试了对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.

  1. I tried to avoid this using null-forgiving operator ! var cid = Request!.Headers["CId"];, it's saying same error.

  2. 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()!;

huangapple
  • 本文由 发表于 2023年5月11日 19:26:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76227108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定