I have the following code:
var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonbytes);
var claims = keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString()));
As you can see my ide shows me a Nullable warning.
I know that I have to check if a variable is null before using it to get rid of such a warning. But I don't know how to do it with dynamic variables in a linq query..?
I hope someone can show me how I can avoid such a warning in this situation.
CodePudding user response:
The IDE gives you this warning as this variable might be null
when it hits this line.
If you are fully confident that this will never be the case, you can use the !
to escape these warnings:
keyValuePairs!.Select(kvp => new Claim(kvp.Key, kvp.Value!.ToString()));
CodePudding user response:
as pazcal said already i can use a ! after the object to escape such a warning. Many thanks for that hint.
Anyway, i've changed my function now to this:
private IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
{
if(jwt!=null && !String.IsNullOrEmpty(jwt)) {
var payload = jwt.Split('.')[1];
var jsonbytes = ParseBase64WithoutPadding(payload);
var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonbytes);
if(keyValuePairs!=null && keyValuePairs.Count > 0) {
var claims = keyValuePairs!.Select(kvp => new Claim(kvp.Key!, kvp.Value!.ToString()!));
return claims;
} else {
throw new Exception("Error while deserializing jwt json string.");
}
} else {
throw new Exception("jwt value cannot be empty or null");
}
}
I hope, that this is safe now :-)
Many thanks for your help.