无法将带有 [] 的索引应用于 "ISession" 类型的表达式

Cannot apply indexing with [] to an expression of type "ISession"

这个片段出现了问题,但我真的不知道为什么(代码来自教程 https://www.youtube.com/watch?v=b0CrSerID1A&list=PLjCTEYO9N-j0wMr_p9j92lfgbY4E9c_Ds&index=16

PICTURE of problem

public string GetCartId(HttpContext context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] =
                        context.User.Identity.Name;
                }
                else
                {

                    Guid tempCartId = Guid.NewGuid();

                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Http;


namespace DogSupreme.Models
{
    public class ShoppingCart 
    {

        private ContextClass accsess = new ContextClass();
        string ShoppingCartId { get; set; }
        public const string CartSessionKey = "CartId";
        public static ShoppingCart GetCart(HttpContext context)
        {
            var cart = new ShoppingCart();
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }
        // Helper method to simplify shopping cart calls
        public static ShoppingCart GetCart(Microsoft.AspNetCore.Mvc.Controller controller)
        {
            return GetCart(controller.HttpContext);
        }
        public void AddToCart(Product item)
        {

            var cartItem = accsess.Carts.SingleOrDefault(
                c => c.CartId == ShoppingCartId
                && c.ItemId == item.ProductId);

            if (cartItem == null)
            {

                cartItem = new Cart
                {
                    ItemId = item.ProductId,
                    CartId = ShoppingCartId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };
                accsess.Carts.Add(cartItem);
            }
            else
            {

                cartItem.Count++;
            }

            accsess.SaveChanges();
        }
        public int RemoveFromCart(int id)
        {

            var cartItem = accsess.Carts.Single(
                cart => cart.CartId == ShoppingCartId
                && cart.RecordId == id);

            int itemCount = 0;

            if (cartItem != null)
            {
                if (cartItem.Count > 1)
                {
                    cartItem.Count--;
                    itemCount = cartItem.Count;
                }
                else
                {
                    accsess.Carts.Remove(cartItem);
                }

                accsess.SaveChanges();
            }
            return itemCount;
        }

        public void EmptyCart()
        {
            var cartItems = accsess.Carts.Where(
                cart => cart.CartId == ShoppingCartId);

            foreach (var cartItem in cartItems)
            {
                accsess.Carts.Remove(cartItem);
            }

            accsess.SaveChanges();
        }
        public List<Cart> GetCartItems()
        {
            return accsess.Carts.Where(
                cart => cart.CartId == ShoppingCartId).ToList();
        }
        public int GetCount()
        {

            int? count = (from cartItems in accsess.Carts
                          where cartItems.CartId == ShoppingCartId
                          select (int?)cartItems.Count).Sum();

            return count ?? 0;
        }

        public decimal GetTotal()
        {

            decimal? total = (from cartItems in accsess.Carts
                              where cartItems.CartId == ShoppingCartId
                              select (int?)cartItems.Count *
                              cartItems.Product.Price).Sum();

            return total ?? decimal.Zero;
        }

        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();

            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetail
                {
                    ItemId = item.ItemId,
                    OrderId = order.OrderId,
                    UnitPrice = item.Product.Price,
                    Quantity = item.Count
                };

                orderTotal += (item.Count * item.Product.Price);

                accsess.OrderDetails.Add(orderDetail);

            }

            order.Total = orderTotal;


            accsess.SaveChanges();

            EmptyCart();

            return order.OrderId;
        }

        public string GetCartId(HttpContext context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] =
                        context.User.Identity.Name;
                }
                else
                {

                    Guid tempCartId = Guid.NewGuid();

                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }
        public void MigrateCart(string userName)
        {
            var shoppingCart = accsess.Carts.Where(
                c => c.CartId == ShoppingCartId);

            foreach (Cart item in shoppingCart)
            {
                item.CartId = userName;
            }
            accsess.SaveChanges();
        }
    }
}

您可以使用 extension methods (Microsoft.AspNetCore.Http.Extensions) 获取或设置字符串会话密钥:

public string GetCartId(HttpContext context)
{
    var session = context.Session;

    if (!session.Keys.Contains(CartSessionKey))
    {
        var userName = context.User.Identity.Name;

        if (!string.IsNullOrWhiteSpace(userName))
        {
            session.SetString(CartSessionKey, userName);
        }
        else
        {
            Guid tempCartId = Guid.NewGuid();
            session.SetString(CartSessionKey, tempCartId.ToString())
        }
    }
    return session.GetString(CartSessionKey);
}

否则你应该手动将字符串与字节数组相互转换


稍微重构代码以将 cartId 生成与会话分开:

public string GetCartId(HttpContext context)
{
   ​var cartId = context.Session.GetString(CartSessionKey);
   ​if (cartId == null)
   ​{
      cartId = GetUserCartId(context.User.Identity.Name);
      ​context.Session.SetString(CartSessionKey, cartId);
   ​}

   return cartId;
}  


​private void GetUserCartId(string userName)
{
   if (!string.IsNullOrWhiteSpace(userName))
      return userName;

   var tempCartId = Guid.NewGuid();
   return tempCartId.ToString();
}