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

Razor Pages删除CartItems后OnGet方法出现空引用异常

问题分析与解决方案

核心问题

你的代码存在两个关键问题,导致点击删除按钮后触发空引用异常:

  1. OnGet方法未处理Cookie值为空/无效的场景:当购物车最后一个商品被删除后,若Cookie被清空或存储的内容无法反序列化为有效列表,Request.Cookies[CookieName]会返回null,此时JavaScriptSerializer.Deserialize<List<CartItem>>(null)会得到null,后续遍历CartItems就会触发空引用异常。
  2. OnGetRemoveFromCart方法未做空值防护:如果Cookie不存在,反序列化会得到null,调用cartItems.FirstOrDefault时会直接报错。

修复后的代码

public class CartModel : PageModel
{
    public List<CartItem> CartItems;
    public const string CookieName = "cart-items";

    public void OnGet()
    {
        var serializer = new JavaScriptSerializer();
        var value = Request.Cookies[CookieName];
        
        // 处理Cookie不存在或值为空的情况,初始化空列表避免null
        CartItems = string.IsNullOrEmpty(value) 
            ? new List<CartItem>() 
            : serializer.Deserialize<List<CartItem>>(value) ?? new List<CartItem>();
        
        foreach (var item in CartItems)
            item.TotalItemPrice = item.UnitPrice * item.Count;
    }

    public IActionResult OnGetRemoveFromCart(long id)
    {
        var serializer = new JavaScriptSerializer();
        var value = Request.Cookies[CookieName];
        
        // 初始化空列表,避免Cookie为空时反序列化得到null
        var cartItems = string.IsNullOrEmpty(value)
            ? new List<CartItem>()
            : serializer.Deserialize<List<CartItem>>(value) ?? new List<CartItem>();
        
        var itemToRemove = cartItems.FirstOrDefault(x => x.Id == id);
        if (itemToRemove != null) // 仅找到商品时执行移除操作
            cartItems.Remove(itemToRemove);
        
        var options = new CookieOptions { Expires = DateTime.Now.AddDays(2) };
        // 即使列表为空,也序列化空列表写入Cookie,避免Cookie丢失
        Response.Cookies.Append(CookieName, serializer.Serialize(cartItems), options);
        
        return RedirectToPage("/Cart");
    }
}

额外优化建议

  • 替换废弃的JavaScriptSerializer:该类已被官方标记为废弃,推荐使用.NET内置的System.Text.Json或第三方库Newtonsoft.Json进行序列化/反序列化,示例(使用System.Text.Json):
    // 序列化
    JsonSerializer.Serialize(cartItems)
    // 反序列化
    JsonSerializer.Deserialize<List<CartItem>>(value) ?? new List<CartItem>()
    
  • 简化Cookie操作:无需先删除旧Cookie,直接用新值覆盖即可,减少不必要的步骤。

内容的提问来源于stack exchange,提问作者zahra rfe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:21:00