how to access session variable in ASP.Net MVC

2019-07-10 04:32发布

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

The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type)

SO LINK REFERRED

1条回答
混吃等死
2楼-- · 2019-07-10 05:15

From the documentation (my emphasis):

You can use the as operator to perform certain types of conversions between compatible reference types or nullable types

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"];
查看更多
登录 后发表回答