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

x
?
Solved

http handler to check null requests .NET 3.0

Posted on 2009-04-28
1
Medium Priority
?
288 Views
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.
Thanks,

0
Comment
Question by:melinalt
1 Comment
 
LVL 1

Accepted Solution

by:
melinalt earned 0 total points
ID: 24423948
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:

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

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()
        MyBase.New()
    End Sub
 
    Protected Overrides Sub OnInit(ByVal e As EventArgs)
        MyBase.OnInit(e)
        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
                    Response.Redirect("~/Default.aspx")
                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)))))))
        'ctx.Response.Write(errorInfo)
        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)
        'ctx.Server.ClearError()
    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 <from@email.com>", "to@email.com")
        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 = "xxx.xxx.xxx.xx"
        mailClient.UseDefaultCredentials = True
        'mailClient.Credentials = basicAuthenticationInfo
        mailClient.Send(Email)
 
    End Sub
 
    Private Sub Dispose() Implements System.Web.IHttpModule.Dispose
 
    End Sub
 
End Class

Open in new window

0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
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…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses
Course of the Month19 days, 21 hours left to enroll

873 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