.NET Core 2 Web项目添加商品到购物车时触发空引用异常
Let's walk through the key issues causing your "Object reference not set to an instance of an object" error, and how to fix them:
1. Incorrect Null Check in the Controller
Your AddPCarrinho method is checking if produtId != null, but produtId is a value type (Guid)—it can never be null. This means even if no product is found in your repository (resulting in produto = null), your code will still try to call carrinho.AddItem(produto, 1), which triggers the null reference when accessing produto.ProdutoID in the AddItem method.
Fix:
Replace the null check to validate the fetched product instead:
public RedirectToActionResult AddPCarrinho(Guid produtId, string returnUrl) { Produto produto = repositorio.All .FirstOrDefault(p => p.ProdutoID == produtId); // Check if the product exists, not the Guid parameter if (produto != null) { Carrinho carrinho = GetCarrinho(); carrinho.AddItem(produto, 1); SalvarCarrinho(carrinho); } return RedirectToAction("Index", new { returnUrl }); }
2. Mismatched Form Parameter and Controller Argument Name
Your view uses asp-for="ProdutoID" which generates an input with name="ProdutoID", but your controller expects a parameter named produtId (note the missing "o"). ASP.NET Core's model binding relies on name matching, so this mismatch will cause produtId to default to Guid.Empty, leading to produto being null.
Fix (choose one):
- Rename the controller parameter to match the form field:
ORpublic RedirectToActionResult AddPCarrinho(Guid ProdutoID, string returnUrl) - Update the view's hidden input to use the controller's parameter name:
<input type="hidden" name="produtId" value="@Model.ProdutoID" />
3. Ensure GetCarrinho() Returns a Valid Instance
You didn't include the code for GetCarrinho(), but if it returns null when the cart doesn't exist in the session, calling carrinho.AddItem(...) will throw a null reference immediately.
Correct Implementation:
Make sure the method initializes a new cart if none exists in the session:
private Carrinho GetCarrinho() { Carrinho carrinho = HttpContext.Session.GetJson<Carrinho>("Carrinho"); if (carrinho == null) { carrinho = new Carrinho(); HttpContext.Session.SetJson("Carrinho", carrinho); } return carrinho; }
4. Add Defensive Checks in the Carrinho Class
To prevent future null references, add a check for the produto parameter in your AddItem method:
public virtual void AddItem(Produto produto, int quantidade) { if (produto == null) { throw new ArgumentNullException(nameof(produto), "Cannot add a null product to the cart."); // Or use return; if you prefer to silently ignore invalid requests } CartLine line = lineCollection .Where(p => p.Produto.ProdutoID == produto.ProdutoID) .FirstOrDefault(); if (line == null) { lineCollection.Add(new CartLine { Produto = produto, Quantidade = quantidade }); } else { line.Quantidade += quantidade; } }
Apply these fixes one by one, and your shopping cart should work without the null reference exception.
内容的提问来源于stack exchange,提问作者mr.cinza

