Solved

Automatically checking a session value in every page_load

Posted on 2006-07-12
24
252 Views
Last Modified: 2012-08-13
I have an application with lots of pages.  I'd like to know if there is a way to have each page check for a particular session value before/during the page_load event?

I know I can manually code the check into each page, but is there anything a little more advanced that can be done so that I only have to code it in once?
0
Comment
Question by:Rouchie
  • 11
  • 7
  • 4
  • +1
24 Comments
 
LVL 8

Expert Comment

by:spongie
ID: 17091058
Hi Rouchie. Two quick ones:

1) Create a page class with your session value checking code for page_load event and let all of your pages inherit from it.
2) Use master pages.

:)
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17091112
Hi spongie
Could you please provide a code example for option 1?  In some of my pages I use code-behind, in others I code the server-side stuff directly in.
Would option 1 work with my existing approach?
0
 
LVL 8

Expert Comment

by:spongie
ID: 17091322
First you need to create a base class for your webpage like below:
-------------------
Imports Microsoft.VisualBasic

Public Class BasePage
    Inherits Page


    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Response.Write("Hello World")
    End Sub
End Class
-----------------

Then on your Code behind files:
-----
Partial Class _Default
    Inherits System.Web.UI.Page

End Class
-------

Or using inline code (take note of first line):
-------
<%@ Page Language="VB" Inherits="BasePage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>
</html>
-------
0
 
LVL 9

Assisted Solution

by:zaghaghi
zaghaghi earned 100 total points
ID: 17091339
if you use vs 2005, its simple that you use a master page,

but if you want to use the second one, it's a sample code:

Imports System
Imports System.Diagnostics

Namespace yournamespace

    Public Class BasePage

        Inherits System.Web.UI.Page


    ' handle page load event here

    End Class 'BasePage

End Namespace


then change the other pages code behind that use this class for inheritance instead of System.Web.UI.Page

0
 
LVL 9

Expert Comment

by:zaghaghi
ID: 17091360
Oooops, i type later ;)

there is another way that is the best is using HttpModules,

so it can handle all http requests, and when you write one http modules there are no places to change.

0
 
LVL 8

Expert Comment

by:rodmjay
ID: 17091369
I would use http modules to do this
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17091642
Okay I get the class approach.  Can someone tell me a little more about modules?  I'm all for not repeating code!
0
 
LVL 9

Expert Comment

by:zaghaghi
ID: 17091697
0
 
LVL 9

Expert Comment

by:zaghaghi
ID: 17091720
http modules :

                                |                              |              |                              |
http request ------>    |     http module 1     | ------>   |     http module 2      | ---------> Http handler( aspx handler)
                                |                              |              |                              |
0
 
LVL 8

Assisted Solution

by:rodmjay
rodmjay earned 400 total points
ID: 17092855
Here's a little insight

Forms Authentication does exactly the same thing you are talking about and uses an http module.

When the request comes in, one of the very things that happens is that the request passes through the forms authentication module.  The module code then looks at the session variable to see the user is authenticated/authorized to do certian things.  If they are, then the request keeps on going to the http handler (usually aspx), otherwise redirect to a login page.  Basically your code will perform similar functionalty minus the authentication/authorization functionality.
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17093578
Thanks for the insight there.  I'm actually using VB, but I'll read the article anyway in the morning and see if I can figure my way through it.
Unless someone attempts it here first of course... :-)
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17108830
Before I start reading the page about creating a httpModule, can I just clarify one thing?  There is one page in my application that will not require this httpModule affecting it, and that is the file the module will redirect the user to (same as the authentication process).  Will this work okay, or will I end up in a never-ending redirect cycle?!?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 25

Author Comment

by:Rouchie
ID: 17121961
Hi All
I'm going to have to request help on this one again unfortunately as I'm in way over my head.  

Can anyone assist in helping to create the module that will perform a check to see if a session value exists before allowing the page to load?

As this exists alongside authentication, can the module expand on the functionality already present for authentication?  I see in Intellisense that there's a HttpApplication.AddOnAuthenticateRequestAsync event, but I don't understand how it works?

Is this the correct approach still, or am I better off creating a fresh module from scratch to work independantly?
0
 
LVL 8

Expert Comment

by:rodmjay
ID: 17124537
Im creating the code right now... give me a few minutes
0
 
LVL 8

Accepted Solution

by:
rodmjay earned 400 total points
ID: 17124947
This should work...

Imports Microsoft.VisualBasic

Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Collections
Imports System.Web.SessionState
Imports System.Text
Imports System.IO
Imports System.ComponentModel

Public Class MyModule
    Implements IHttpModule

    Public Sub New()
    End Sub

    Public Sub Init(ByVal ctx As HttpApplication) Implements System.Web.IHttpModule.Init
        AddHandler ctx.PreRequestHandlerExecute, AddressOf context_PreRequestHandlerExecute
        AddHandler ctx.PostRequestHandlerExecute, AddressOf context_PostRequestHandlerExecute
    End Sub

    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
    End Sub

    Private Sub context_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
        CaptureSessionContent()
    End Sub

    Private Sub CaptureSessionContent()
        Dim ctx As HttpContext = HttpContext.Current
        Dim session As HttpSessionState = ctx.Session

        If session("item") Is Nothing Then

            'Do the processing here

        End If

    End Sub

End Class

Dont to forget to add a section to the web config like this...

    <httpModules>
      <add type="MyModule" name="SomeModuleName"/>
    </httpModules>

to aviod confusion, add this right after the pages attribute.
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17128190
Thanks for that rodmjay.  There's just one error thrown though.  I think it's because there's no actual sub that is referenced in the PostRequestHandlerExecute...

Name 'context_PostRequestHandlerExecute' is not declared
Line 20:  AddHandler ctx.PostRequestHandlerExecute, AddressOf context_PostRequestHandlerExecute
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17128195
Also, if I wrap the class inside a namespace, do I need to include that namespace info in web.config?  i.e.

<add type="MyNS.MyModule" name="SomeModuleName"/>
0
 
LVL 8

Expert Comment

by:rodmjay
ID: 17130604
yes, very true, delete the delegate for the postrequesthandler and you should be good, all you need is the prerequesthandler one.  The web.config you are showing should work.  if not,  you will want to google httpmodule web.config and you can get the correct syntax.
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17130904
Okay I think it's plugged in.  The problem is I get a browser error in Firefox:

>>The page isn't redirecting properly
>>Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

Would this be because the module would affect EVERY page in the application?  If so, I'd need the module to ignore login.aspx as that is the destination page for redirection after the session value has been checked.
0
 
LVL 8

Expert Comment

by:rodmjay
ID: 17131164
I am a little unclear on what your application is supposed to do... you asked for something that checks for the session variable for each page...  What I would do, which i cant go into much detail is user a marker interface for the pages that dont require to have session variable checked

Something like INoSessionCheck

This interface will have no methods, but in your logic, see if the page implements this interface, if so skip the Session checker logic.  you will also probably have to use the postrequesthandler to do this, since the page object isnt created at this phase in the request.  I would start a new thread for this if you have any questions and ill help you the most i can.
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17137061
Sorry for any confusion.  I am using forms authentication on the pages, starting from login.aspx
The login page verifies the user then creates an authentication ticket that contains the user's role.  On top of that I then store an integer in a session variable which represents further information about their account.
Now, forms authentication automatically checks for the authentication ticket prior to each page loading, but, I wanted to also incorporate a check for the session value at the same time.  This was where I presumed a httpmodule would come in.

I know that in each page I could do:

sub page_load(....)
   if not session("myVal") is nothing then...

but I wanted to avoid having to re-code that on every single page.
0
 
LVL 8

Expert Comment

by:rodmjay
ID: 17138852
Thats fine.  Did you try my proposed solution?
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17139161
Okay rodmjay, I posted this as another question.  Please let me share the rest of your knowledge on this matter! :-)

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_21924662.html
0
 
LVL 25

Author Comment

by:Rouchie
ID: 17152526
Sorry to be a pest, but could you please take a look at the follow-up question and let me know your thoughts?  Thanks.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now