Skip to main content

Fixed: "The requested operation requires an element of type 'Number', but the target element has type 'String'" from TryGetPayloadValue in .NET C#

· 10 min read
Jagdish Kumawat
Founder @ Dewiride

JsonWebToken.TryGetPayloadValue<int[]> should return false when a JWT claim isn't a list of whole numbers. In Microsoft.IdentityModel.JsonWebTokens 8.25.0, it throws an InvalidOperationException instead when the list holds text, and the exception stops the whole program. Reading the claim as a JsonElement and checking each item yourself avoids it.

What I Was Doing​

I was checking how TryGetPayloadValue handles claims of the wrong type, for the C# part of the JWT course's Custom Claims tutorial. A list of IDs is a common claim, and services don't always agree on whether IDs are numbers or text. To show the problem on its own, I made a console app with the .NET 10.0.404 SDK and Microsoft.IdentityModel.JsonWebTokens 8.25.0:

Terminal
dotnet new console -o album-ids
cd album-ids
dotnet package add Microsoft.IdentityModel.JsonWebTokens

The program creates and validates two tokens with an album_ids claim: one with the numbers [7, 12], and one with the same IDs as text, ["7", "12"]. Then it reads the claim with TryGetPayloadValue<int[]>:

Program.cs
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;

// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
var key = new SymmetricSecurityKey(Convert.FromBase64String("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64="));
var handler = new JsonWebTokenHandler();

// One token whose album_ids are numbers, and one whose album_ids are text.
await ShowAlbumIdsAsync(new object[] { 7, 12 });
await ShowAlbumIdsAsync(new object[] { "7", "12" });

async Task ShowAlbumIdsAsync(object[] albumIds)
{
var token = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = "https://login.example.org",
Audience = "https://photos.example.org",
Claims = new Dictionary<string, object> { ["album_ids"] = albumIds },
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256),
});
var result = await handler.ValidateTokenAsync(token, new TokenValidationParameters
{
IssuerSigningKey = key,
ValidIssuer = "https://login.example.org",
ValidAudience = "https://photos.example.org",
});
if (!result.IsValid)
{
throw result.Exception;
}
var jwt = (JsonWebToken)result.SecurityToken;

if (jwt.TryGetPayloadValue<int[]>("album_ids", out var ids))
{
Console.WriteLine($"album_ids: {string.Join(", ", ids)}");
}
else
{
Console.WriteLine("album_ids: not a list of whole numbers");
}
}
  • ShowAlbumIdsAsync creates a token whose album_ids claim holds the values it's given, validates it, and reads the claim back.
  • jwt.TryGetPayloadValue<int[]>("album_ids", out var ids) asks for the claim as an array of int, and returns true or false.

Then I ran it:

Terminal
dotnet run

What I Expected​

album_ids: 7, 12 for the first token, and album_ids: not a list of whole numbers for the second. A Try method returns false when it can't do what you ask: Microsoft Learn's page for JsonWebToken.TryGetPayloadValue says it returns "true if successful, false otherwise". It does that for single values: asking for a text claim such as name as an int returns false.

What I Got​

The first token worked. The second stopped the program:

Output
album_ids: 7, 12
Unhandled exception. System.InvalidOperationException: The requested operation requires an element of type 'Number', but the target element has type 'String'.
at System.Text.Json.ThrowHelper.ThrowJsonElementWrongTypeException(JsonTokenType expectedType, JsonTokenType actualType)
at System.Text.Json.JsonDocument.TryGetValue(Int32 index, Int32& value)
at Microsoft.IdentityModel.Tokens.Json.JsonSerializerPrimitives.TryCreateTypeFromJsonElement[T](JsonElement jsonElement, T& t)
at Microsoft.IdentityModel.JsonWebTokens.JsonClaimSet.GetValue[T](String key, Boolean throwEx, Boolean& found)
at Microsoft.IdentityModel.JsonWebTokens.JsonClaimSet.TryGetValue[T](String key, T& value)
at Microsoft.IdentityModel.JsonWebTokens.JsonWebToken.TryGetPayloadValue[T](String key, T& value)
at Program.<>c__DisplayClass0_0.<<<Main>$>g__ShowAlbumIdsAsync|0>d.MoveNext() in /Users/Shared/you/album-ids/Program.cs:line 34
--- End of stack trace from previous location ---
at Program.<Main>$(String[] args) in /Users/Shared/you/album-ids/Program.cs:line 11
at Program.<Main>(String[] args)

A zsh terminal where dotnet run prints album_ids: 7, 12, then stops with an unhandled System.InvalidOperationException: The requested operation requires an element of type 'Number', but the target element has type 'String', thrown from JsonSerializerPrimitives.TryCreateTypeFromJsonElement inside JsonWebToken.TryGetPayloadValue.

What I Checked​

The stack trace. It runs from JsonWebToken.TryGetPayloadValue through JsonClaimSet.TryGetValue and JsonSerializerPrimitives.TryCreateTypeFromJsonElement to JsonDocument.TryGetValue(Int32 index, Int32& value), which threw. So the exception came from inside IdentityModel, not from my code.

The IdentityModel source. For an int[], TryCreateTypeFromJsonElement calls TryGetInt32 on each item of the array, then tries to parse the item's text, and returns false when both fail. long[] works the same way with TryGetInt64.

What TryGetInt32 does with text. Microsoft Learn's page for JsonElement.TryGetInt32 lists an InvalidOperationException when "This value's ValueKind is not Number." So for an item like "7", it throws before IdentityModel's return false can run.

Other cases. long[] threw the same exception. An array holding true threw it with 'True' at the end, and an array holding null with 'Null'. An array of decimals such as [7, 12.5] returned false, because 12.5 is still a number. A claim that isn't there returned false too.

The newest code. The same lines are on IdentityModel's dev branch, so I reported it as issue #3699. Until a fixed version ships, the code has to work around it.

Why It Happens​

TryGetPayloadValue<int[]> reads each item of the array with JsonElement.TryGetInt32, which is meant only for JSON numbers and throws for anything else. Nothing checks the item's kind first, so an item that's text, true, false or null makes it throw instead of returning false.

The Fix​

Read the claim as a JsonElement, the System.Text.Json type that can hold any JSON value, and check it yourself: that it's an array, and that every item is a number that fits in an int. TryGetPayloadValue<JsonElement> doesn't throw: it returns true for an array, and false for a claim that isn't there or that holds a single string or number.

At the top of Program.cs, add:

Program.cs
using System.Text.Json;

System.Text.Json holds JsonElement and JsonValueKind. At the bottom, add this method:

Program.cs
// TryGetPayloadValue<int[]> throws when an item isn't a number, so read the claim as JSON and check each item first.
static bool TryGetIntArray(JsonWebToken jwt, string name, out int[] values)
{
values = [];
if (!jwt.TryGetPayloadValue<JsonElement>(name, out var claim) || claim.ValueKind != JsonValueKind.Array)
{
return false;
}
var numbers = new List<int>();
foreach (var item in claim.EnumerateArray())
{
if (item.ValueKind != JsonValueKind.Number || !item.TryGetInt32(out var number))
{
return false;
}
numbers.Add(number);
}
values = [.. numbers];
return true;
}
  • values = []; gives values an empty array, which is what the caller gets when the method returns false.
  • TryGetPayloadValue<JsonElement>(name, out var claim) reads the claim as JSON. claim.ValueKind != JsonValueKind.Array turns away anything that isn't a list, null included.
  • item.ValueKind != JsonValueKind.Number checks each item before TryGetInt32 can throw. TryGetInt32 then turns away numbers that aren't whole or don't fit in an int.
  • values = [.. numbers]; copies the list into an array.

Then use it where the code read the claim:

Program.cs
if (TryGetIntArray(jwt, "album_ids", out var ids))

The complete Program.cs:

Program.cs with a TryGetIntArray method that reads the claim with TryGetPayloadValue of JsonElement, returns false unless it's an array, and returns false for any item whose ValueKind isn't Number or that TryGetInt32 can't read, used in ShowAlbumIdsAsync in place of TryGetPayloadValue of int array.

Program.cs
using System.Text.Json;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;

// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
var key = new SymmetricSecurityKey(Convert.FromBase64String("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64="));
var handler = new JsonWebTokenHandler();

// One token whose album_ids are numbers, and one whose album_ids are text.
await ShowAlbumIdsAsync(new object[] { 7, 12 });
await ShowAlbumIdsAsync(new object[] { "7", "12" });

async Task ShowAlbumIdsAsync(object[] albumIds)
{
var token = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = "https://login.example.org",
Audience = "https://photos.example.org",
Claims = new Dictionary<string, object> { ["album_ids"] = albumIds },
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256),
});
var result = await handler.ValidateTokenAsync(token, new TokenValidationParameters
{
IssuerSigningKey = key,
ValidIssuer = "https://login.example.org",
ValidAudience = "https://photos.example.org",
});
if (!result.IsValid)
{
throw result.Exception;
}
var jwt = (JsonWebToken)result.SecurityToken;

if (TryGetIntArray(jwt, "album_ids", out var ids))
{
Console.WriteLine($"album_ids: {string.Join(", ", ids)}");
}
else
{
Console.WriteLine("album_ids: not a list of whole numbers");
}
}

// TryGetPayloadValue<int[]> throws when an item isn't a number, so read the claim as JSON and check each item first.
static bool TryGetIntArray(JsonWebToken jwt, string name, out int[] values)
{
values = [];
if (!jwt.TryGetPayloadValue<JsonElement>(name, out var claim) || claim.ValueKind != JsonValueKind.Array)
{
return false;
}
var numbers = new List<int>();
foreach (var item in claim.EnumerateArray())
{
if (item.ValueKind != JsonValueKind.Number || !item.TryGetInt32(out var number))
{
return false;
}
numbers.Add(number);
}
values = [.. numbers];
return true;
}

After the Fix​

Terminal
dotnet run
Output
album_ids: 7, 12
album_ids: not a list of whole numbers

A zsh terminal where dotnet run prints album_ids: 7, 12 and then album_ids: not a list of whole numbers.

Both tokens were read. The one with text IDs got the answer the code was written for, instead of an exception.

Common Mistakes​

MistakeWhat happensDo this instead
Catching the InvalidOperationException around TryGetPayloadValue<int[]>It works, but the code depends on an exception the method isn't meant to throw, which may change when the bug is fixedCheck the items yourself, as TryGetIntArray does
Switching to long[]The same exception, from TryGetInt64Use the same method with TryGetInt64 and long
Calling item.TryGetInt32 without checking item.ValueKind firstThe same exception, now from your own codeCheck item.ValueKind == JsonValueKind.Number first
Expecting "7" to be read as 7Learn's page for TryGetInt32 says: "This method does not parse the contents of a JSON string value."Agree with the service that makes the token to send numbers

Troubleshooting​

SymptomLikely causeFix
System.InvalidOperationException: The requested operation requires an element of type 'Number', but the target element has type 'String'. from TryGetPayloadValueAn array claim holds text where numbers were expectedRead it with TryGetIntArray
The same message, ending in 'True', 'False' or 'Null'The array holds true, false or nullThe same method
TryGetIntArray returns false for [7, 12.5]12.5 isn't a whole numberExpected: the claim isn't a list of whole numbers

FAQ​

Is this a bug in my code?​

No. The method's documentation says it returns false when it can't give you the value, and it does for single values. Only arrays whose items aren't numbers make it throw, from inside IdentityModel.

Does reading the claim as a string array have the same problem?​

Not for numbers: asked for [7, 12] as a string[], TryGetPayloadValue returned true with the items "7" and "12".

Will the fix still work when IdentityModel is fixed?​

Yes. TryGetIntArray doesn't depend on the bug: it only uses TryGetPayloadValue<JsonElement> and checks the items itself. I'll update this post when a fixed version ships.

Conclusion​

TryGetPayloadValue<int[]> and TryGetPayloadValue<long[]> throw in IdentityModel 8.25.0 when an item of the array isn't a number. Until that's fixed, read the claim as a JsonElement, check that it's an array, and check each item's ValueKind before you read it as a number.

Additional Resources​