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

Time:12-21

Problem arises in this snippet, but i dont really know why(code is from a tutorial 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();
        }
    }
}

CodePudding user response:

You can use extension methods (Microsoft.AspNetCore.Http.Extensions) to get or set string session keys:

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);
}

Otherwise you should manually convert strings to and from byte array


Slightly refactored code to split cartId generation from working with session:

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();
}
  • Related