Fixed: "The requested operation requires an element of type 'Number', but the target element has type 'String'" from TryGetPayloadValue in .NET C#
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:
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[]>:
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");
}
}
ShowAlbumIdsAsynccreates a token whosealbum_idsclaim 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 ofint, and returnstrueorfalse.
Then I ran it:
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:
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)

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:
using System.Text.Json;
System.Text.Json holds JsonElement and JsonValueKind. At the bottom, add this method:
// 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 = [];givesvaluesan empty array, which is what the caller gets when the method returnsfalse.TryGetPayloadValue<JsonElement>(name, out var claim)reads the claim as JSON.claim.ValueKind != JsonValueKind.Arrayturns away anything that isn't a list,nullincluded.item.ValueKind != JsonValueKind.Numberchecks each item beforeTryGetInt32can throw.TryGetInt32then turns away numbers that aren't whole or don't fit in anint.values = [.. numbers];copies the list into an array.
Then use it where the code read the claim:
if (TryGetIntArray(jwt, "album_ids", out var ids))
The complete 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
dotnet run
album_ids: 7, 12
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
| Mistake | What happens | Do 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 fixed | Check the items yourself, as TryGetIntArray does |
Switching to long[] | The same exception, from TryGetInt64 | Use the same method with TryGetInt64 and long |
Calling item.TryGetInt32 without checking item.ValueKind first | The same exception, now from your own code | Check item.ValueKind == JsonValueKind.Number first |
Expecting "7" to be read as 7 | Learn'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
| Symptom | Likely cause | Fix |
|---|---|---|
System.InvalidOperationException: The requested operation requires an element of type 'Number', but the target element has type 'String'. from TryGetPayloadValue | An array claim holds text where numbers were expected | Read it with TryGetIntArray |
The same message, ending in 'True', 'False' or 'Null' | The array holds true, false or null | The same method |
TryGetIntArray returns false for [7, 12.5] | 12.5 isn't a whole number | Expected: 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
- IdentityModel issue #3699, the report of this problem.
- JsonWebToken.TryGetPayloadValue, on Microsoft Learn.
- JsonElement.TryGetInt32 and JsonValueKind, on Microsoft Learn.
