Reputation: 143
I want to make a class to retrieve data from session state, am doing as following is it correct way?
I have make a static class and static methods to get data
[AuthorizeMember]
public class TestController : Controller
{
public ActionResult list()
{
Session["memberid"] = 12345;
return View();
}
public ActionResult iteminfo(string prodcode)
{
int memberid=SessionData.MemberTableId();
}
}
public static class SessionData
{
public static int MemberTableId()
{
return Convert.ToInt32(HttpContext.Current.Session[memberid]);
}
}
Upvotes: 0
Views: 137
Reputation: 5634
Static class will serve same contents on all logged in sessions.
Avoid using static classes in web application unless you completely understand how it is going to work.
Option 1:
You can either directly put values in session as shown in your code sample.
The advantage is you dont need to write any wrapper.
The disadvantage is anybody will keep on adding any value to session and after your application grows, nobody will know which data you are keeping in session.
Option 2:
OR you can create a single class to hold all session values together.
Whenever you want to read session value always read from this class.
Mark this class as serializable, so that in future, if you want to keep your session state in SQL Server or on some other server like REDIS cache, then it would just be minimal configuration change.
That way you will always know what all values you put in the session.
For ex. You can have a class to hold all your session values
[Serializable] //// This is required when using out of proc session state
public class MySessionState
{
public string Username {get; set;}
public string Role {get; set;}
public string FirstName{get; set;}
public string LastName {get; set;}
public int Age{get; set;}
}
Create a const key to refer this class object
public const string MySessionObjectKey = "mysessionstate";
Then in your controller actions you can use it like this:
public void MyAction()
{
var sessionState = Session[MySessionObject] as MySessionState;
if (sessionState == null)
{
sessionState = new MySessionState();
}
sessionState.FirstName = "SomeName";
sessionState.LastName = "SomeOtherName";
/// Process this session object
Session[MySessionObjectKey] = sessionState;
}
Hope this helps you.
Upvotes: 2