Session changes done in application_Error rolled back after redirect

前端 未结 5 1551
感情败类
感情败类 2021-01-26 05:01

I have an asp.net application and I am trying to handle custom exception using Application_Error. It works nicely but I have new requirement to set the error data in Session obj

5条回答
  •  梦毁少年i
    2021-01-26 05:48

    I've just come across this problem myself and, after a couple of hours of messing around, managed to solve it. The issue is that Application_Error() clears the session after executing as part of some sort of "cleanup" routine which you need to stop.

    The solution I found is as follows:

    1. Call Server.ClearError(); - this clears the last error from the application and stops the "cleanup" taking place, thus preserving session.

    2. The (unwanted imho) side-effect of this is that it no longer performs the automatic redirect to the error page, so you need to explicitly call Response.Redirect("~/error.aspx");

    So, something like this:

    protected void Application_Error(object sender, EventArgs e)
    {
        // Grab the last exception
        Exception ex = Server.GetLastError();
    
        // put it in session
        Session["Last_Exception"] = ex;
    
        // clear the last error to stop .net clearing session
        Server.ClearError();
    
        // The above stops the auto-redirect - so do a redirect!
        Response.Redirect("~/error.aspx");
    }
    

    If you don't want to hard-code the URL, you could grab the defaultRedirect URL directly from the customerrors section in the web.config, which would give you something like this:

    protected void Application_Error(object sender, EventArgs e)
    {
        // Grab the last exception
        Exception ex = Server.GetLastError();
    
        // put it in session
        Session["Last_Exception"] = ex;
    
        // clear the last error to stop .net clearing session
        Server.ClearError();
    
        // The above stops the auto-redirect - so do a redirect using the default redirect from the customErrors section of the web.config!
        var customerrors = (CustomErrorsSection)WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");
        Response.Redirect(customerrors.DefaultRedirect);
    }
    

提交回复
热议问题