Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Session' does not exist in the current context

I have the following code, that uses session but i have an error in the line :

if (Session["ShoppingCart"] == null)

the error is cS0103: The name 'Session' does not exist in the current context what is the problem ?

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Collections.Generic;
using System.Web.SessionState;
/// <summary>
/// Summary description for ShoppingCart
/// </summary>
public class ShoppingCart
{
    List<CartItem> list;
    public ShoppingCart()
    {
        if (Session["ShoppingCart"] == null)
            list = new List<CartItem>();
        else
            list = (List<CartItem>)Session["ShoppingCart"];
    }
}
like image 651
Adham Avatar asked Aug 06 '11 23:08

Adham


2 Answers

Use

if (HttpContext.Current == null || 
    HttpContext.Current.Session == null || 
    HttpContext.Current.Session["ShoppingCart"] == null)

instead of

if (Session["ShoppingCart"] == null)
like image 160
Peter Avatar answered Nov 15 '22 17:11

Peter


The issue is that your class does not inherit from Page. you need to Change

public class ShoppingCart

to

public class ShoppingCart : Page

and it will work

like image 39
Jeff Avatar answered Nov 15 '22 18:11

Jeff