【发布时间】:2019-11-12 20:36:07
【问题描述】:
我正在使用 ASP.NET Core。如何在静态方法中使用会话变量?
在 ASP.NET 中,这看起来像这样:
protected static string AssignSession()
{
return HttpContext.Current.Session["UserName"].ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
Session["UserName"] = "super user";
}
当我在 ASP.NET Core 中尝试时,我收到以下错误:
非静态字段、方法需要对象引用, 或属性“ControllerBase.HttpContext”。
【问题讨论】:
-
先生,我在问 Asp.net-core。
-
试试
System.Web.HttpContext.Current.Session[...] -
首先,为什么要使用静态方法?其次,在 ASP.NET Core 中没有静态 HttpContext 实例,也没有
Page_Load事件 - 根本没有事件。 HttpContext 现在是控制器或 PageModel 的属性。在您也可以使用它之前,您将拥有to enable Session。如果您想以其他方法访问 Session 对象,则必须将其作为参数传递
标签: c# asp.net-core