views:

302

answers:

1

Essentially I want to be able to catch when a user lets their session timeout and then clicks on something that ends up causing an Async postback. I figured out that if I put this code in my Session_Start (in Global.asax) then I can catch a postback that occurred during a session timeout:

    With HttpContext.Current
        If TypeOf .Handler Is Page Then
            Dim page As Page = CType(.Handler, Page)
            If page IsNot Nothing AndAlso page.IsPostBack Then
                'Session timeout
            End If
        End If
    End With

This works fine. My question is, I would like to be able to inject some javascript into the Response and then call Response.End() so that the rest of the application does not get finish executing. The problem is that when I try Response.Write("<script ... ") followed by Response.End() then javascript does not get written to the response stream. I'm sure there are other places in the application that I can safely write Javascript to the Response but I can't let the rest of the application execute because it will error when it tries to access the session objects.

To sum up: I need to inject javascript into the response in the Session_Start event in Global.asax

Note: You may be wondering why I'm not doing this in Session_End...we don't use InProc sessions and so Session_End doesn't get called...but that's beside the point...just wanted to make it clear why I'm doing this in Session_Start.

+1  A: 

Writing to the response stream outside of an HttpHandler is generally not a good idea; it may work in some corner cases, but it's not how things are intended to work.

Have you considered using either a Page base class or a Page Adapter to do this? That way, you would only need one copy of the code, and it could be applied to either all pages or just the ones you select.

Another option would be to use URL rewriting to redirect the incoming request to a page that generates the script output you need.

RickNZ
Thanks for the advice. Do you know of a way to safely redirect without using Response.Redirect()? The reason I ask is because we are running into errors whenever we attempt to perform a Response.Redirect during an AJAX callback (e.g. when Page.IsCallBack is true) and in this section of code we will generally only need to take care of the timeout when it's a callback.
Adam
One approach is URL rewriting, which is done by calling context.RewritePath(newPath). Another is Server.Transfer(newPath). RewritePath() is best before you get to the Page, Server.Transfer() is best after that.
RickNZ
Perfect thanks!
Adam