如何在ASP.Net MVC中访问会话变量 [英] how to access session variable in ASP.Net MVC
问题描述
我有一个ASP.Net MVC 5 Web应用程序,我想在会话中设置一个变量,以便以后可以访问它.由于我是初学者,所以我不知道该如何实现.下面是我尝试过的
I have a ASP.Net MVC 5 web application and I want to set a variable in the session so that I can access it later. As I am a beginner I don't know how to achieve it. Below is what I have tried
clsUser user = mdlUser.GetUserForSession();
System.Web.HttpContext.Current.Session["MyValue"] = user.SessionID; // user.SessionID is an integer
int x = System.Web.HttpContext.Current.Session["MyValue"] as int; // Access
但是我收到错误作为错误,
But I get error as Error as
as运算符必须与引用类型或可为null的类型("int"为不可为null的值类型)一起使用
The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type)
推荐答案
来自文档(我的重点):
您可以使用as运算符在兼容的引用类型或可为空的类型之间进行某些类型的转换
You can use the as operator to perform certain types of conversions between compatible reference types or nullable types
int
是值类型,而不是引用类型,因此不能使用as
运算符,因此您需要使用经典"方法来转换值.
int
is a value type, not a reference type, therefore the as
operator cannot be used, so you need the 'classic' method for casting the value.
int x = (int)System.Web.HttpContext.Current.Session["MyValue"];
这篇关于如何在ASP.Net MVC中访问会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!