我正在使用购物车应用程序。我开发了一个使用cookie维护用户购物车的应用程序。它工作得很完美,直到我做了一些UI改变,现在它不工作了,现在我不知道我做错了什么,因为我通过c#后端代码维护cookie没有中断,前端只读取这些cookie并将它们传递到视图模型中以显示在购物车面板上。这是我的代码
Startup.cs
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
添加商品到购物车
public JsonResult AddToShoppingCart(UserProductVM model)
{
try
{
if (string.IsNullOrEmpty(model.SelectedSize))
return Json(new { status = false, msg = "Please select size to proceed." });
var result = ShoppingCartHelper.GetShoppingCartList(model, _httpContextAccessor);
if (result.Status <= 0)
return Json(new { status = false, msg = result.Message });
Response.Cookies.Delete("ShoppingCart");
Response.Cookies.Append("ShoppingCart", JsonConvert.SerializeObject(result.Data));
return Json(new { status = true, msg = "Success! added to shopping cart." });
}
catch (Exception ex)
{
return Json(new { status = false, msg = ex.Message.ToString() });
}
}
Reading From Cart
public static string GetShoppingCartFromCookies(IHttpContextAccessor _httpContextAccessor)
{
return _httpContextAccessor.HttpContext?.Request?.Cookies["ShoppingCart"]?.ToString();
}
一切工作正常,现在没有工作没有饼干被添加到饼干列表。这是相同的代码,我也备份了我的应用程序,当我运行应用程序cookie工作完美,但问题是,这是与旧的设计,我不再使用UI设计。这是在一个应用程序中工作的相同代码,但不能与具有不同UI的另一个应用程序一起工作。
是否已将IHttpContextAccessor添加到依赖容器中?
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
我的问题已经解决了。问题基本上是我在添加base64图像字符串,这是不工作。当我注释这一行时,它工作得很好,不需要修改任何代码。
public static GenericResponseDTO<List<ShoppingCartViewModel>> GetShoppingCartList(UserProductVM model, IHttpContextAccessor _httpContextAccessor)
{
var shoppingcartmodel = new List<ShoppingCartViewModel>();
var cartmodel = new ShoppingCartViewModel
{
RestaurantId = model.RestaurantId,
SubCategoryId = model.SubCategoryId,
RestaurantSubCategoryId = model.RestaurantSubCategoryId,
OrderGuid = Guid.NewGuid(),
Quantity = model.Quantity,
//ItemImage = model.ItemImage,
SelectedSize = model.SelectedSize.Split('-')[0],
SingleItemPrice = Convert.ToDecimal(model.SelectedSize.Split('-')[1]),
SubCategoryName = model.SubCategoryName,
TotalItemPrice = (model.Quantity * Convert.ToDecimal(model.SelectedSize.Split('-')[1]))
};
if (string.IsNullOrEmpty(GetShoppingCartFromCookies(_httpContextAccessor)))
shoppingcartmodel.Add(cartmodel);
else
{
shoppingcartmodel = JsonConvert.DeserializeObject<List<ShoppingCartViewModel>>(GetShoppingCartFromCookies(_httpContextAccessor));
if (shoppingcartmodel.Any(x => x.RestaurantSubCategoryId == model.RestaurantSubCategoryId))
return new GenericResponseDTO<List<ShoppingCartViewModel>> { Data = new List<ShoppingCartViewModel>(), Status = -1, Message = "Item is alreay exists in your cart please remove and add another." };
shoppingcartmodel.Add(cartmodel);
}
return new GenericResponseDTO<List<ShoppingCartViewModel>> { Data = shoppingcartmodel, Status = 1 };
}
我已经评论了ItemImage行,它像一个魅力。也许它能帮助别人解决问题。