how to access session variable in ASP.Net MVC

蓝咒 提交于 2019-12-11 02:56:06

问题


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:


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"];


来源:https://stackoverflow.com/questions/41839234/how-to-access-session-variable-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!