0

I am new to C# and need some help. I have a ASP.Net page that uses the Session variable in several different methods. The Session variable is a UserInfo class used to store user info between pages. I am trying to have one method creates the userinfo class from the Session and returns it to the calling methods. I am sure it can be done I just can't figure it out. Any help will be greatly appreciated.

private void CheckForUserType()
{
    var user = RetrieveSession();
}

private object RetrieveSession()
{
    var userInfo =(UserInfo)HttpContext.Current.Session["userInfo"];
    return userInfo;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 5
    Change the return type from 'object' on RetrieveSession() to 'UserInfo'? – C Smith Aug 22 '18 at 18:17
  • What error or issue are you seeing? – Colin Young Aug 22 '18 at 18:18
  • In C#, you are returning the object not the class. Just an FYI for better question writing in the future. see: https://stackoverflow.com/questions/8550130/what-is-the-difference-between-objects-and-classes-in-c#8550151 – DontThinkJustGo Aug 22 '18 at 18:21
  • returning an object or a class?? a class is an object definition, there's no way to return a "class", the class should be defined in your scope to be able to create an instance (object) out of it. – Mike Aug 22 '18 at 19:02
  • so many terrible casts , change the "var user" for "UserInfo user" change the prive object restrievesession for "Private UserInfo Retrievesession – Mike Aug 22 '18 at 19:04
  • The calling method does not recognize the object returned as the userinfo class. It doesn't see the properties of the class. – Tom Mauldin Aug 22 '18 at 19:06
  • That's because the return type for `RetrieveSession` is defined as `object`. See the first comment... – Rufus L Aug 22 '18 at 19:17

3 Answers3

0

Try new Object...

 private void CheckForUserType()
 {
    var user = RetrieveSession();
 }


 private UserInfo RetrieveSession()
 {
    UserInfo userInfo = new UserInfo(HttpContext.Current.Session["userInfo"]);
    return userInfo;
 }
Any Moose
  • 723
  • 6
  • 12
  • HttpContext.Current.Session acts like a dictionary for objects, so you just need to get the value via the indexer and cast it – C Smith Aug 22 '18 at 18:21
0

You need a small tweak in your code. Change return type from object to UserInfo.

   private UserInfo RetrieveSession()
   {
        var userInfo =(UserInfo)HttpContext.Current.Session["userInfo"];
        return userInfo;
   }

You may need to change your access modifier based on the way you want to use this method.

dj079
  • 1,389
  • 8
  • 14
-1

Like said above return the UserInfo object, and maybe make it public instead of private if you calling it from different areas. I'd be careful with session objects, especially if you're using multiple servers or azure, make sure that you're doing it right. Best to not use session object and user oauth2 owin/katana

Dan P
  • 1
  • 1