Same Properties in Control and Page
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.
If you are using a lot of session variables in the project, I would suggest to have a SessionManager class where you have the getter and setter properties set. So according to your example, as soon as the User logs in you can set the session value. Now you can access this session value from anywhere in your project.
精彩评论