Session["UserId"] = user.Id;
int id = (int)Session["UserId"];
Session["FirstName"] = user.FirstName;
string fName = (string)Session["FirstName"];
As you might imagine, your project could get fairly convoluted if you are accessing the same (or many different) session variable across many different pages throughout your application. Using explicit string values as your keys can also cause problems if you accidentally typo when entering them or decide to change one later. Throw several developers into the mix and this can turn into a nightmare.
You can alleviate some of this frustration by using an enum that contains all of your session key values. This allows you to make changes much easier, provides a quick reference to what objects you have in the session, and makes calls to the session variable consistent. The new session calls (with the help of an enum) would look like this.
enum SessionKeys {
UserId = 1,
FirstName = 2
}
Session[SessionKeys.UserId .ToString()] = user.Id;
int id = (int)Session[SessionKeys.UserId .ToString()];
Session[SessionKeys.FirstName .ToString()] = user.FirstName;
string fName = (string)Session[SessionKeys.FirstName .ToString()];
public static class SessionFacade {
public static int UserId {
get {
return (int)Session[SessionKeys.UserId.ToString()];
}
set {
Session[SessionKeys.UserId.ToString()] = value;
}
}
public static string FirstName {
get {
return (string)Session[SessionKeys.FirstName.ToString()];
}
set {
Session[SessionKeys.FirstName.ToString()] = value;
}
}
}
int id = SessionFacade.UserId;
SessionFacade.UserId = user.Id;
string fName = SessionFacade.FirstName;
SessionFacade.FirstName = user.FirstName;
3 comments:
use the same technique for the ViewState and the QueryString and you're good to go
it´s a good idea,
How does it work in asp.net?
Sorry by my english, but i try to learn.
The class can put in the app_data folder from the web site?
thanks
see you
Yes. The SessionFacade would go with your other classes in the app_data. You could then use the SessionFacade class to interact with the Session instead of using the Session object directly.
Like the poster above said. You could use this same strategy to wrap the ViewState and QueryString to provide the same benefits.
Post a Comment