"会话"在当前上下文中不存在

Adh*_*ham 10 c# asp.net session

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

if (Session["ShoppingCart"] == null)
Run Code Online (Sandbox Code Playgroud)

错误是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"];
    }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 41

使用

if (HttpContext.Current == null || 
    HttpContext.Current.Session == null || 
    HttpContext.Current.Session["ShoppingCart"] == null)
Run Code Online (Sandbox Code Playgroud)

代替

if (Session["ShoppingCart"] == null)
Run Code Online (Sandbox Code Playgroud)

  • 但我得到这个异常System.NullReferenceException .. !! (2认同)

Jef*_*eff 16

问题是您的类不会从Page继承.
更改公共类ShoppingCart

到公共类ShoppingCart:Page

它会起作用

  • 当页面不是页面时,继承页面似乎不是一个合适的解决方案...... (10认同)

Amy*_*Amy 8

您需要Page通过继承PageSession传入或使用将您的类转换为a HttpContext.Current.Session.

  • 但我得到这个异常System.NullReferenceException .. !! (2认同)