You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redis购物车存储失败:CartItem缺失brand、type字段求助

Redis购物车无法存储问题求助

问题概述

前端提交购物车数据时,后端抛出JSON反序列化错误:Error parsing cart data: JSON deserialization for type 'Cart-Item' was missing required properties, including the following: brand, type。Postman测试Get/Post/Delete接口均返回200 OK,但前端提交的Payload显示CartItem缺少brand和type字段,购物车ID已通过nanoid生成,但数据未存入Redis。

相关代码

后端Infrastructure层CartService代码

using Core.Entites;
using Core.Interfaces;
using StackExchange.Redis;
using System.Text.Json;

namespace Infrastructure.Services
{
    public class CartService(IConnectionMultiplexer redis) : ICartService
    {
        private readonly IDatabase _database = redis.GetDatabase();
        public async Task<bool> DeleteCartAsync(string key)
        {
            return await _database.KeyDeleteAsync(key);
        }

        public async Task<ShoppingCart?> GetCartAsync(string key)
        {
            var data = await _database.StringGetAsync(key);
            return data.IsNullOrEmpty ? null : JsonSerializer.Deserialize<ShoppingCart>(data!);
        }

        public async Task<ShoppingCart?> SetCartAsync(ShoppingCart cart)
        {
            var created = await _database.StringSetAsync(cart.Id, JsonSerializer.Serialize(cart),
             TimeSpan.FromDays(30));
            if (!created) return null;
            return await GetCartAsync(cart.Id);
        }
    }
}

后端API层CartController代码

using Core.Entites;
using Core.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace API.Controllers 
{
    public class CartController : BaseAPIController 
    {
        private readonly ICartService _cartService;
        private readonly JsonSerializerOptions _jsonOptions;
        private readonly ILogger<CartController> _logger;

        public CartController(ICartService cartService, ILogger<CartController> logger)
        {
            _cartService = cartService;
            _logger = logger;  // Fixed: Correctly assign logger to _logger
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
        }

        [HttpGet]
        public async Task<ActionResult<ShoppingCart>> GetCartById(string id)
        {
            var cart = await _cartService.GetCartAsync(id);
            return Ok(cart ?? new ShoppingCart { Id = id, Items = new List<CartItem>() });
        }

        [HttpPost]
        public async Task<ActionResult<ShoppingCart>> UpdateCart([FromBody] JsonElement cartData)
        {
            try
            {
                // Log the raw JSON
                _logger.LogInformation("Received cart data: {CartData}", cartData.GetRawText());

                ShoppingCart? cart = null;
                if (cartData.TryGetProperty("ms", out var msProperty))
                {
                    // Handle the case where the cart data is nested under 'ms'
                    _logger.LogInformation("Cart data nested under 'ms' property");
                    var items = JsonSerializer.Deserialize<List<CartItem>>(msProperty.GetRawText(), _jsonOptions);
                    cart = new ShoppingCart { Id = Guid.NewGuid().ToString(), Items = items ?? new List<CartItem>() };
                }
                else
                {
                    // Try to deserialize directly to ShoppingCart
                    _logger.LogInformation("Attempting to deserialize directly to ShoppingCart");
                    cart = JsonSerializer.Deserialize<ShoppingCart>(cartData.GetRawText(), _jsonOptions);
                }

                if (cart == null)
                {
                    _logger.LogWarning("Failed to deserialize cart data");
                    return BadRequest("Invalid cart data");
                }

                // Log the deserialized cart
                _logger.LogInformation("Deserialized cart: {@Cart}", cart);

                // Ensure Id is set
                if (string.IsNullOrEmpty(cart.Id))
                {
                    cart.Id = Guid.NewGuid().ToString();
                }

                var updatedCart = await _cartService.SetCartAsync(cart);
                
                if (updatedCart == null) return BadRequest("Problem updating the cart");

                return Ok(updatedCart);
            }
            catch (JsonException ex)
            {
                _logger.LogError(ex, "Error parsing cart data");
                return BadRequest($"Error parsing cart data: {ex.Message}");
            }
        }

        [HttpDelete]
        public async Task<ActionResult> DeleteCart(string id)
        {
            var result = await _cartService.DeleteCartAsync(id);
            if (!result) return BadRequest("Problem deleting the cart");
            return Ok();
        }
    }
}

Angular前端cart-item.ts代码

export type ICartItem = {
    productId: number;
    productName: string; 
    price: number;
    quantity: number;
    pictureUrl: string;
    brand: string;
    type: string;
}

export class Cart implements ICart {
    id = nanoid();
    items: ICartItem[] = [];
}   

已完成的排查操作

  • 重启客户端与API服务器
  • 检查代码语法错误
  • 重写购物车服务代码
  • 添加日志模块获取Redis服务器信息

核心问题点

  1. 前端提交的Payload中CartItem缺少brand和type字段,导致后端反序列化失败
  2. 购物车ID已生成,但数据未能存入Redis

内容的提问来源于stack exchange,提问作者Kevon Cooper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 22:04:51