'best practice to solve dereference of possibly null reference in .Net6 web api

I do have the following code and I get the dereference of a possibly null reference which is understandable . what I do not know is the best way to solve the issue , (shown warning is CS8602 Deference of a possibly null reference)

public class ClaimService : IClaimService

{ private readonly IHttpContextAccessor _httpContextAccessor;

public ClaimService(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

public string GetLoggedInUserId()
{
   return 
        _httpContextAccessor
        .HttpContext
        .User
        .Claims
        .FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")
        .Value;            
}

public string? GetLoggedInUserRole()
{
    return _httpContextAccessor
       .HttpContext
       .User
       .Claims
       .FirstOrDefault(x => x.Type == ClaimTypes.Role)
       .Value;
         
}

}

of coarse , i can use ? to remove the error like below , but i am not happy with this approach .

public class ClaimService : IClaimService { private readonly IHttpContextAccessor _httpContextAccessor;

public ClaimService(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

public string? GetLoggedInUserId()
{
   return 
        _httpContextAccessor?
        .HttpContext?
        .User?
        .Claims?
        .FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?
        .Value;            
}

public string? GetLoggedInUserRole()
{
    return _httpContextAccessor?
       .HttpContext?
       .User?
       .Claims?
       .FirstOrDefault(x => x.Type == ClaimTypes.Role)?
       .Value;
         
}

}

can anybody help me on the best possible approach ,

many thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source