C# – Accessing SessionState in IHttpModule after 404

asp.netc

Is it possible to access SessionState in the Error event handler of a HttpModule following a 404?

Im trying to implement a consistent error handling mechanism for both full and partial postbacks using the technique described in this blog post,

ASP.NET Error Handling……

Instead of passing loads of parameters on the query string im trying to push the exception into session state and access it from the error page.

SessionState is never available at point I do my Server.Transfer (in error handler of HttpModule) so not available to error page.

Ive tried the trick of resetting the IHttpHandler to one with the IRequestSessionState interface but no joy.

Thanks in advance,

EDIT – The code of the IHttpModule error handler is,

void context_Error(object sender, EventArgs e)
{
    try
    {            
        var srcPageUrl = HttpContext.Current.Request.Url.ToString();                       

        // If the error comes our handler we retrieve the query string
        if (srcPageUrl.Contains(NO_PAGE_STR))
        {
            // Deliberate 404 from page error handler so transfer to error page
            // SESSION NOT AVAILABLE !!!!

            HttpContext.Current.ClearError();                
            HttpContext.Current.Server.Transfer(string.Format("{0}?ErrorKey={1}", ERROR_PAGE_URL, errorKey), true);
        }
        else            
            HttpContext.Current.Server.ClearError();                

        return;
    }
    catch (Exception ex)
    {
        Logging.LogEvent(ex);
    }
} 

Matt

Best Answer

    public class ExceptionModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {

        }

    /// <summary>
    /// Init method to register the event handlers for 
    /// the HttpApplication
    /// </summary>
    /// <param name="application">Http Application object</param>
    public void Init(HttpApplication application)
    {
        application.Error += this.Application_Error;
    }




    private void Application_Error(object sender, EventArgs e)
    {

                    // Create HttpApplication and HttpContext objects to access
                    // request and response properties.
                    var application = (HttpApplication)sender;
                    var context = application.Context;
                    application.Session["errorData"] = "yes there is an error";

                    context.Server.Transfer("Error.aspx");

         }
}

This should do the trick! works for me!

Related Topic