Adham
Adham

Reputation: 64904

'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"];
    }
}

Upvotes: 15

Views: 80914

Answers (5)

bhavsar japan
bhavsar japan

Reputation: 125

If you want to use session directly then simply add the following namespace:

using system.web.mvc

Upvotes: 0

Sayed Abolfazl Fatemi
Sayed Abolfazl Fatemi

Reputation: 3921

In my case only try-catch block fix problem, like this:

protected void Application_AcquireRequestState(object sender, EventArgs e)
    {
        /// Using from Try-Catch to handle "Session state is not available in this context." error.
        try
        {
            //must incorporate error handling because this applies to a much wider range of pages 
            //let the system do the fallback to invariant 
            if (Session["_culture"] != null)
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Session["_culture"].ToString());
                //it's safer to make sure you are feeding it a specific culture and avoid exceptions 
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Session["_culture"].ToString());
            }
        }
        catch (Exception ex)
        {}
    }

Upvotes: 0

Jeff
Jeff

Reputation: 2071

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

Upvotes: 17

Peter
Peter

Reputation: 38555

Use

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

instead of

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

Upvotes: 47

user47589
user47589

Reputation:

You either need to convert your class to a Page by inheriting from Page, or have the Session passed in, or use HttpContext.Current.Session.

Upvotes: 9

Related Questions