The following code gives me this error: The type initializer for 'System.IdentityModel.Tokens.Jwt.JsonExtensions' threw an exception.

handler = new JwtSecurityTokenHandler();
tokenStringEngineer = handler.WriteToken(token); // this line causes the error

InnerException gives details on the error:

at System.IdentityModel.Tokens.Jwt.JwtPayload.SerializeToJson()
 at System.IdentityModel.Tokens.Jwt.JwtPayload.Base64UrlEncode()
 at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
 at my-file.cs:line 519

Before that, I had issues with nuget packages, specially Microsoft.IdentityModel.Tokens

See my previous question here: Could not load file or assembly 'Microsoft.IdentityModel.Tokens - problem

Now, with that installed, I get this new error.

I found that the version of Newtonsoft.Json could affect it, so I tried versions 10 to 13, but the error remains. Other suggestions I found did not solve my issue.

So I ask here, any ideas what I can try?

It is a solution with 3 projects, where only one project uses the JSON and Token functions.

1

There are 1 answers

0
Sonnich Jensen On

I was missing the package System.IdentityModel.Tokens.Jwt

I found the solution by searching more and found this:

Error generating JWT token during ASP.NET Core Web API authorization

It works now