"Request" object not available within a Class? RRS feed

  • Question

  • User-164210933 posted

    Got some vb.net code that authenticates a user, and sets a session variable, works fine. Wrapped all the security stuff into a Class to maintain in one place rather than duplicating across many pages. Getting the message that "Request not available within this context" when trying to capture the visitor's IP. Works fine inside the Page_Load event, just not inside a Class called from within Page_Load.

    Is the Request object not available within a Class? (Would I have to pass the object to the Class?)

    Here is a snip of the codebehind, the class, and the error - thanks for any insight & discussion, cheers!

    === index.aspx.vb ==========================================
    Imports MyApp.SecurityCheck

    Public Class index
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    '--------- this works fine when uncommented
    'If Session("VisitorIP") Is Nothing Then Session("VisitorIP") = Request.UserHostAddress.ToString()
    Dim MySecurityCheck As New SecurityCheck
    End Sub

    End Class

    === SecurityCheck.VB ==========================================
    Public Class SecurityCheck
    Inherits System.Web.UI.Page
    Public Sub RunChecks()
    '--------- this blows up when uncommented, unless session variable already set
    ' If Session("VisitorIP") Is Nothing Then Session("VisitorIP") = Request.UserHostAddress.ToString()
    End Sub
    End Class

    === the error message ==========================================
    System.Web.HttpException: 'Request is not available in this context'
    This exception was originally thrown at this call stack:
    MyApp.SecurityCheck.RunChecks() in SecurityCheck.VB
    MyApp.index.Page_Load(Object, System.EventArgs) in Index.Aspx.vb
    System.Web.UI.Page.ProcessRequestMain(bool, bool)


    Tuesday, February 11, 2020 5:45 PM


  • User-164210933 posted

    Answered my own question, instead of:




    That said, if you have any insight why the HttpContext / Request object isn't directly available within a Class, I'd love to get a better understanding. Cheerio!

    "The Tim"

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 11, 2020 8:07 PM