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

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

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 description for ShoppingCart ///  public class ShoppingCart { List list; public ShoppingCart() { if (Session["ShoppingCart"] == null) list = new List(); else list = (List)Session["ShoppingCart"]; } } 

问题是您的类不会从Pageinheritance。
更改公共类ShoppingCart

到公共类ShoppingCart:Page

它会起作用

使用

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

代替

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

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

萨拉姆。

在我的情况下,只有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) {} } 

从破碎的页面创建新页面并粘贴其中的所有内容都不起作用。 什么工作关闭Visual Studio并重新打开它。 之后破碎的页面工作了

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

using system.web.mvc