I have created a base class for my pages, where I can get/set certain Session properties.
public class MyBasePage : System.Web.UI.Page
{
public MyUser SessionUser
{
get
{
return (MyUser) Session["User"];
}
set
{
Session["User"] = value;
}
}
}
(I know ASP.NET Membership provides a User class, but I can’t use Membership for legacy reasons atm.)
I can easily access these properties from every page now, but I need them in some controls as well. I see two options now:
- Get the page from the control and cast it to MyBasePage. Access the property then.
- Duplicate the code in a BaseControl class and inherit the control from this. (obviously flawed because of duplicate code)
- Use a static class and put the properties there. (using HttpContext.Current.Session)
- something else?
What’s the best approach?
I would definitely go for option 3 and use a static class. This saves your pages and control from having to inherit just for a simple method/property call.
Your comment in option 2 is why you shouldn’t have gone for the inheritance approach in the first place. Option 1, is just taking option 2 and making it harder to manage.