ASP.NET Core Web API授权时JWT令牌生成失败问题
JWT令牌生成抛出TypeLoadException问题排查与解决
问题描述
在Web API的授权获取令牌环节,执行请求时触发未处理异常:
An unhandled exception has occurred while executing the request. System.TypeInitializationException: The type initializer for System.IdentityModel.Tokens.Jwt.JsonExtensions' threw an exception. System.TypeLoadException: Could not load type 'Microsoft.IdentityModel.Json.JsonConvert' from assembly 'Microsoft.IdentityModel.Tokens, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
错误触发点为令牌生成代码的return new JwtSecurityTokenHandler().WriteToken(tokenOptions);行,预期接口返回200状态码并包含令牌和刷新令牌。
相关代码
令牌生成服务代码
using ASFT.Auth.Interfaces; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Cryptography; namespace ASFT.Auth.Services { public class TokenService : ITokenService { public string GenerateAccessToken(IEnumerable<Claim> claims) { var signinCredentials = new SigningCredentials(AuthOptions.Key, SecurityAlgorithms.HmacSha256); var tokenOptions = new JwtSecurityToken( issuer: AuthOptions.Issuer, audience: AuthOptions.Audience, claims: claims, expires: DateTime.Now.AddHours(48), signingCredentials: signinCredentials); return new JwtSecurityTokenHandler().WriteToken(tokenOptions); } } }
已安装的NuGet依赖
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.11" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.11" /> <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="7.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.11"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets></PackageReference>
解决方案
这个错误的核心原因是依赖版本不匹配:Microsoft.AspNetCore.Authentication.JwtBearer(7.0.11)与Microsoft.IdentityModel.Tokens(7.0.0)版本不一致,导致内部类型引用失败。
按照以下步骤修复:
- 同步依赖版本
将Microsoft.IdentityModel.Tokens的版本升级至7.0.11,与JwtBearer保持一致,修改后的依赖配置如下:
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="7.0.11" />
- 清理并重建项目
删除项目根目录下的bin和obj文件夹,然后重新构建项目,确保缓存的旧版本文件被清除。 - 确认NuGet包还原
右键项目选择「还原NuGet包」,等待所有依赖包完成下载和安装。
完成以上操作后,重新运行项目并调用授权接口,即可正常生成JWT令牌,接口返回200状态码及预期的令牌内容。
内容的提问来源于stack exchange,提问作者Pro Vak
相关产品推荐
相关产品推荐

