9

I'm trying to set a cookie in Application_EndRequest in Global.asax.vb as suggested in ASP.NET OutputCache and Cookies

I've written the following code, cookie gets ERROR value.

Why isn't session available?

Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)
    Dim context As HttpContext = HttpContext.Current
    If Not context.Session Is Nothing Then
        context.Response.Cookies("T").Value = context.Session("T")
    Else
        context.Response.Cookies("T").Value = "ERROR"
    End If
End Sub
KyleMit
  • 30,350
  • 66
  • 462
  • 664
JNF
  • 3,696
  • 3
  • 31
  • 64

1 Answers1

16

The session does not exist anymore in the Application_EndRequest event.

Application_PostRequestHandlerExecute is called after the code from your application is executed but before the SessionState is released.

Sub Application_PostRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
    Dim context As HttpContext = HttpContext.Current
    If Not context.Session Is Nothing Then
        context.Response.Cookies("T").Value = context.Session("T")
    Else
        context.Response.Cookies("T").Value = "ERROR"
    End If
End Sub
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Yan Brunet
  • 4,727
  • 2
  • 25
  • 35
  • I'm looking for something that executes after each HTTP request, I thought `Application_EndRequest` does that. Session shouldn't be released between requests, only at the end of the session. – JNF Jan 29 '13 at 07:36
  • 3
    It's not the session that is released, but the SessionState, it's control is returned to the server. This event is fired for each request, just after you handled the request (aka "your code"). – Yan Brunet Jan 29 '13 at 10:59