Search code examples
c#asp.net-core-webapi.net-6.0coverity

getting static code analysis tool error "Calling a method on null object base.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?


Solution

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