[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 272
  • Last Modified:

Automatically checking a session value in every page_load

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
Rouchie
Asked:
Rouchie
  • 11
  • 7
  • 4
  • +1
3 Solutions
 
spongieCommented:
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
 
RouchieAuthor Commented:
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
 
spongieCommented:
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Hamed ZaghaghiCommented:
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
 
Hamed ZaghaghiCommented:
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
 
rodmjayCommented:
I would use http modules to do this
0
 
RouchieAuthor Commented:
Okay I get the class approach.  Can someone tell me a little more about modules?  I'm all for not repeating code!
0
 
Hamed ZaghaghiCommented:
0
 
Hamed ZaghaghiCommented:
http modules :

                                |                              |              |                              |
http request ------>    |     http module 1     | ------>   |     http module 2      | ---------> Http handler( aspx handler)
                                |                              |              |                              |
0
 
rodmjayCommented:
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
 
RouchieAuthor Commented:
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
 
RouchieAuthor Commented:
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
 
RouchieAuthor Commented:
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
 
rodmjayCommented:
Im creating the code right now... give me a few minutes
0
 
rodmjayCommented:
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
 
RouchieAuthor Commented:
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
 
RouchieAuthor Commented:
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
 
rodmjayCommented:
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
 
RouchieAuthor Commented:
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
 
rodmjayCommented:
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
 
RouchieAuthor Commented:
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
 
rodmjayCommented:
Thats fine.  Did you try my proposed solution?
0
 
RouchieAuthor Commented:
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
 
RouchieAuthor Commented:
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 11
  • 7
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now