登录管理器<TUser>。PasswordSignInAsync() 正在抛出 System.Text.Json 对象循环异常



几天前,我决定将旧的API项目从.net core 2.0重写为3.1,但今天我遇到了一个无法解决的错误。重写"AccountManager"类_signInManager.PasswordSignInAsync((后开始抛出与Json对象循环连接的错误。

例外:

((System.Text.Json.JsonException(ex(.消息:检测到不支持的可能的对象循环。这可能是由于周期,或者如果对象深度大于32的最大允许深度。

用法示例:

public class AccountManager : IAccountManager{
public ApplicationUser ActualUser { get; private set; }
private readonly SignInManager<ApplicationUser> _signInManager;
public AccountManager(SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
}
public async Task<LoginResponseDTO> LoginAsync(LoginRequestDTO input)
{
var result = await _signInManager.PasswordSignInAsync(input.Email, input.Password, false, true);
...
}
}

启动:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
...
var builder = services.AddIdentityCore<ApplicationUser>(u =>
{
...
})
.AddEntityFrameworkStores<RBDbContext>().AddDefaultTokenProviders()
.AddSignInManager<UserManager<ApplicationUser>>()
.AddUserManager<UserManager<ApplicationUser>>();
builder.AddEntityFrameworkStores<RBDbContext>().AddDefaultTokenProviders();
services.AddScoped<IAccountManager,AccountManager>();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

我甚至尝试使用用户和其他类的属性[JsonIgnore],但没有成功。应用程序用户类别:

public class ApplicationUser : IdentityUser
{
public string Avatar { get; set; }
...
[JsonIgnore]
public virtual ICollection<Order> Orders{ get; set; }
[JsonIgnore]
public virtual ICollection<Participation> Participations{ get; set; }
[JsonIgnore]
public virtual ICollection<UserProduct> UserProducts{ get; set; }
}

UserManager来自Microsoft.Extension.Identity.Core,版本=3.1.2.0

检测到可能的对象循环,这是不受支持的。这可能是由于周期,或者如果对象深度大于32的最大允许深度。

在ASP.NET Core 3.0+中,默认情况下,它使用System.Text.Json进行JSON序列化,而Newtonsoft.Json的某些功能可能无法与System.Text.JSON一起正常工作(例如,Newtonsoft.JSON默认情况下没有最大深度限制(,这可能会导致此问题。

您可以尝试安装Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet包,以添加对基于Newtonsoft.Json的格式化程序和功能的支持,并检查它是否适用于您。

services.AddControllersWithViews().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});

此外,您还可以在这里找到Newtonsoft.Json和System.Text.Json之间的区别:https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#table-newtonsoftjson和systemtextjson 之间的差异

最新更新