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

bwleehnv  于 2023-05-08  发布在  .NET
关注(0)|答案(5)|浏览(146)

我有下面的代码,它使用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"];
    }
}
3wabscal

3wabscal1#

使用

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

而不是

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

mzsu5hc02#

问题是你的类没有从Page继承。你需要改变

public class ShoppingCart

public class ShoppingCart : Page

一定会成功的

soat7uwm

soat7uwm3#

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

9rnv2umw

9rnv2umw4#

在我的例子中,只有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)
        {}
    }
tuwxkamq

tuwxkamq5#

如果你想直接使用session,只需添加以下命名空间:

using system.web.mvc

相关问题