Efficient Session Access Solutions

A collegue asked me a question which came from his friend. He asked the following question:

I have several pages in which I have to access the following code. I want to avoid to put all this code in every page that exists in my web application.

Private user As User</em>

‘###Loading user parameters (ID, Name, AccessRights,…)
user = Session("user")
If user Is Nothing Then
user = New User
End If

There are several solutions to this issue. I will describe 2 solutions which do the job, this does not mean that there are no other even more efficient solutions possible.

If you need a code example (both C#.NET and VB.NET) for both solutions just send me an email: wouter@goedvriend.com

Solution 1:

- Create a MasterPage with a public property which encapsulates the code to get the User from the Session.
- Add the MasterType directive to each page which needs to access the user property:

< %@ MasterType VirtualPath="~/[YourMasterPage].master" %>

This casts the Page.Master object automatically to the type of your masterpage and this results in the possibility of accessing the public user property.

MSDN link with full explanation.

Solution 2:
- Declare an Interface with a getter property with type User and have your MasterPage implement it.
- Insert the code to get the User from the Session into the getter from the interface declared.
- When calling the Page.Master cast the object to the interface you declared.
- Access the public user property through the casted object.

Conclusion:
Both solutions have the same result. The first is the default asp.net 2.0 solution and is only suitable when puting your general accessable code in your masterpage. Solution 2 gives you some more freedom implementation and decouples your functionality. Other elements in your application are able to implement this interface, so you are never entangled to your masterpage implementation.

2 Responses to “Efficient Session Access Solutions”

  1. GILBERT says:


    MedicamentSpot.com. Canadian Health&Care.Best quality drugs.No prescription online pharmacy.Special Internet Prices. High quality pills. Order pills online

    Buy:Seroquel.Ventolin.Buspar.Amoxicillin.Advair.Nymphomax.Lipothin.SleepWell.Benicar.Zetia.Female Pink Viagra.Aricept.Lipitor.Prozac.Cozaar.Zocor.Wellbutrin SR.Lasix.Acomplia.Female Cialis….

Leave a Reply