WebAPI: Standard way of using session object in server methods

Standard

The best common way to use session objects in MVC and WebAPI ‘enterprise web’ project is to load them into public class soon after successful logging, then save that loaded data class into session object and utilize this session object in mvc and webapi controller using static method so that one persistent ‘typecast’ object is available for each online user.

If we don’t use above method, then you have to use HttpContext.Current.Session[“Test”] everywhere in project and then type cast it into relative object for smooth execution of operation. Typecast object will help you to use object directly in LINQ queries where they consumed strongly typed variables only in filtering clause

Please note data class is not static only method which will invoke session object will be static, point to ponder if data class is made static then all online user will access information of recent logged in user. (don’t even think of implementing static data class on production server, otherwise … 😀 😀 )

So here is the deal:

  1. Create new data class
    public class CandidateInfoModels
        {
            public int ImportedCandidate_OID
            {
                get;
                set;
            }
        }

    2. Load data into this object and declare/initialize session objectvar candidateInfo = new CandidateInfoModels
    {
    ImportedCandidate_OID = userExists.ImportedCandidate_OID //perform DB operation using ORM
    };
    System.Web.HttpContext.Current.Session[“CurrentCandidateSession”] = candidateInfo;

3. Time to bring in static method to use session object:

public class CurrentUser
{
  public static CandidateInfoModels GetCurrentUser()
  {
   return (CandidateInfoModels)HttpContext.Current.Session["CurrentCandidateSession"];
  }
}

4. Usage in invoking code:

 var id = CurrentUser.GetCurrentUser().ImportedCandidate_OID
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s