I am the following code:
var token = new JwtBuilder()
.WithAlgorithm(new HMACSHA256Algorithm())
.WithSecret(_Signature)
.AddClaim("test", 3)
.Build();
I would like to add multiple values (called 'claims' here):
.AddClaim("test", 3)
.AddClaim("test2", 4)
.AddClaim("test3", 5)
If I have a dictionary:
Dictionary<string, int> myDictionary;
how can I write the expression so all the values from the dictionary are added? (pseudo code: AddClaim(myDictionary)).
Edit: I'm looking for a method that fits the 'fluent' flow and not an external loop.
It's not entirely clear what you're asking. If you want a method that's in the API you're using, then that's up to the implementors of the API. E.g. maybe you're using Jwt.Net here, you'd have to have something like that added if you want that feature "out-of-the-box".
Otherwise, you can't get out of writing the loop yourself. But, what you can do is encapsulate the loop in an extension method:
static class JwtExtensions
{
public static JwtBuilder AddClaims<TKey, TValue>(this JwtBuilder builder, Dictionary<TKey, TValue> dictionary)
{
foreach (var kvp in dictionary)
{
builder.AddClaim(kvp.Key, kvp.Value);
}
return builder;
}
}
Then you can write something like this:
var token = new JwtBuilder()
.WithAlgorithm(new HMACSHA256Algorithm())
.WithSecret(_Signature)
.AddClaims(myDictionary)
.Build();