使用C#、带身份验证的ASP.NET Core、MongoDB.Diverer和MongoDB.EntityFrameworkCore处理项目. 我正在try 将一个用户ID以字符串形式存储在购物车中,并使用该数据查找购物车.我设法将商品添加到购物车中,当我转到购物车页面并调用get-方法时,它成功地找到了购物车,没有任何问题.问题是,如果我重新启动应用程序,以用户身份登录并再次转到购物车页面,我会收到BSON Desiralization错误:
BsonSerializationException:未知的鉴别器值‘List`1’.
它发生在我调用FirstOrDefaultAsync方法时,我在重启应用程序后收到反序列化错误.
GetItems代码:
public async Task<CartDto> GetItems()
{
var user = signInManager.Context.User.Identity;
if (user is not null && user.IsAuthenticated)
{
var identity = System.Security.Claims.ClaimTypes.NameIdentifier;
var userId = signInManager.Context.User.FindFirst(identity)?.Value;
var userCart = await context.Cart.FirstOrDefaultAsync(c => c.UserId == userId);
if (userCart is not null)
{
CartDto cartDto = new()
{
Id = userCart.Id.ToString(),
UserId = userCart.UserId,
Products = userCart.Products
};
return cartDto;
}
}
}
购物车类,存储在MongoDB中:
[Collection("Cart")]
public class Cart
{
public ObjectId Id { get; set; }
public required string UserId { get; set; }
public List<string> Products { get; set; }
}