http handler to check null requests .NET 3.0

Posted on 2009-04-28
Last Modified: 2013-11-08
I have a VB .NET Web Application (.NET 3.0) which has custom session management (written by another developer).
Some times when the session objects are null the application displays the following error instead of redirecting the user to the login page.
"Object reference not set to an instance of an object".
To get rid of this message, I am thinking on creating an http handler that checks all requests looking for null values (if session object/value is null then redirect user to login page).
Unfortunatelly, I don't have experience with http handlers.
I will appreciate any references, links, code examples regarding how to build this handler.

Question by:melinalt
    1 Comment
    LVL 1

    Accepted Solution

    I created a class called basePageSessionExpire ("Session Expire Class" code below) .  This checks if the session is a new session. if so then redirects the user to the login page (default.aspx). Then, I changes all my pages to inherit from this class:

    Inherits basePageSessionExpire

    Also, for general error handling, I created a class to handle all type of errors called errorHandling (IHttpModule "Error Handling Class" code below) and added the following lines to the web.config page:

        <add name="errorHandling" type="namespace.errorHandling, namespace"/>Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

    This gets the error, logs it into the eventlog and send me an email.

    'Session Expirte Class
    Public Class basePageSessionExpire
        Inherits System.Web.UI.Page
        Public Sub New()
        End Sub
        Protected Overrides Sub OnInit(ByVal e As EventArgs)
            If (Not (Context.Session) Is Nothing) Then
                If Session.IsNewSession Then
                    Dim szCookieHeader As String = Request.Headers("Cookie")
                    If ((Not (szCookieHeader) Is Nothing) AndAlso (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) Then
                    End If
                End If
            End If
        End Sub
    End Class
    'Error Handling Class
    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Text
    Imports System.Web
    Public Class errorHandling
        Implements System.Web.IHttpModule
        Public Sub Init(ByVal app As HttpApplication) Implements System.Web.IHttpModule.Init
            AddHandler app.Error, AddressOf Me.OnError
        End Sub
        Public Sub OnError(ByVal obj As Object, ByVal args As EventArgs)
            ' At this point we have information about the error
            Dim ctx As HttpContext = HttpContext.Current
            Dim exception As Exception = ctx.Server.GetLastError
            Dim errorInfo As String = ("<br><b>Offending URL:</b> " _
                        + (ctx.Request.Url.ToString + ("<br><br><b>Date/Time:</b>" & Now().ToString & "<br><br><b>Source:</b> " _
                        + (exception.Source + ("<br><br><b>Message:</b> " _
                        + (exception.Message + ("<br><br><b>Stack trace:</b> " + exception.StackTrace)))))))
            Dim SiteLogName As String = "ApplicationName"
            ' Write new error log  
            errorEmailNotification(exception, errorInfo)
            If Not EventLog.SourceExists(SiteLogName) Then
                EventLog.CreateEventSource(SiteLogName, SiteLogName)
            End If
            Dim NewLog As EventLog = New EventLog()
            NewLog.Source = SiteLogName
            NewLog.WriteEntry(exception.ToString(), EventLogEntryType.Error)
        End Sub
        Sub errorEmailNotification(ByVal exc, ByVal edetails)
            'Create a new MailMessage object and specify the"From" and "To" addresses
            Dim Email As New System.Net.Mail.MailMessage("Application Error <>", "")
            Email.Subject = "APPLICATION ERROR"
            Email.Body = "<span style='font-family:Verdana;font-size:9pt;'>" & edetails & "</span>"
            Email.IsBodyHtml = True
            Dim mailClient As New System.Net.Mail.SmtpClient()
            'Put your own, or your ISPs, mail server name onthis next line
            mailClient.Host = ""
            mailClient.UseDefaultCredentials = True
            'mailClient.Credentials = basicAuthenticationInfo
        End Sub
        Private Sub Dispose() Implements System.Web.IHttpModule.Dispose
        End Sub
    End Class

    Open in new window


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
    Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
    In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor ( If you're interested in additional methods for monitoring bandwidt…

    779 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

    17 Experts available now in Live!

    Get 1:1 Help Now