我正在使用購物車應用程式。我開發了一個使用 cookie 維護用戶購物車的應用程式。在我進行了一些 UI 更改之前它一直運行良好,現在它無法正常作業我不知道我做錯了什么,因為我通過 c# 后端代碼維護 cookie 沒有中斷,前端只讀取這些 cookie 并傳遞它們進入視圖模型以顯示在購物車面板上。這是我的代碼
啟動檔案
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() });
}
}
從購物車中讀取
public static string GetShoppingCartFromCookies(IHttpContextAccessor _httpContextAccessor)
{
return _httpContextAccessor.HttpContext?.Request?.Cookies["ShoppingCart"]?.ToString();
}
一切正常,現在沒有任何效果,沒有將 cookie 添加到 cookie 串列中。這是相同的代碼,我也備份了我的應用程式,當我運行該應用程式時,cookie 作業正常,但問題是它是舊設計,我不再使用該 UI 設計。這是在一個應用程式中作業但不適用于具有不同 UI 的另一個應用程式的相同代碼。
uj5u.com熱心網友回復:
您是否已將 IHttpContextAccessor 添加到依賴項容器?
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
uj5u.com熱心網友回復:
我已經解決了我的問題。問題基本上是我添加了無效的 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 行發表了評論,它的作用就像一個魅力。也許它可以幫助其他人解決問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/329748.html
