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?
The issue seems to come from
object.ToStringreturningstring?. There is nothing what can be null hereControllerBase.Requestis not nullable,HttpRequest.Headersis not nullable also, (thoughHttpRequesthas properties marked as nullable reference types likeContentType).IHeaderDictionary.Item[String]also returns non-nullableStringValues:Try:
Or