“会话”在当前上下文中不存在

时间:2011-08-06 23:01:40

标签: c# asp.net session

我有以下代码,它使用会话但我在行中有错误:

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

错误是cS0103: The name 'Session' does not exist in the current context有什么问题?

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

5 个答案:

答案 0 :(得分:41)

使用

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

而不是

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

答案 1 :(得分:16)

问题是您的班级不会继承自Page 更改 公共类ShoppingCart

到公共类ShoppingCart:Page

它会起作用

答案 2 :(得分:7)

您需要通过继承Page或将Page传入,或使用Session将您的班级转换为HttpContext.Current.Session

答案 3 :(得分:0)

萨拉姆。

在我的情况下,只有try-catch块修复问题,如下所示:

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

答案 4 :(得分:0)

如果您想直接使用会话,只需添加以下命名空间

即可

<强> using system.web.mvc