开发者

Global.asax Session_Start() endless loop

开发者 https://www.devze.com 2023-04-12 17:29 出处:网络
In my Global.asax file, I have the following co开发者_运维技巧de that deals with with unhandled exceptions:

In my Global.asax file, I have the following co开发者_运维技巧de that deals with with unhandled exceptions:

void Application_Error(object sender, EventArgs e)
{
    Application["Exception"] = Server.GetLastError();
    Response.Redirect("ErrorPage.aspx");
}

(ErrorPage.aspx retrieves the exception details from Application, and deals with it.)

Still in Global.asax, I run the following code to check all sorts of user-related stuff:

void Session_Start(object sender, EventArgs e)
{
    ... // All sorts of user-related stuff
}

Normally, both the error redirecting and the user-related-stuff work perfectly fine.

However, if ever an error is thrown during Session_Start, the page is redirected, and Session_Start is called all over again!

This results in an endless loop.

From what I have found here and here, this happens because of some sort of session-cookies issue, which makes the browser and/or server think that the session is restarted at every redirect.

Does anyone know how to resolve the cookie issue?


I would go with setting a flag in the Session_Start telling "don't redirect when error happens", like this:

void Session_Start(object sender, EventArgs e)
{
    Application["DoNotRedirectOnError"] = true
    ... // All sorts of user-related stuff
    Application["DoNotRedirectOnError"] = false
}

Then in the error handling, check for that flag and use Server.Execute instead:

void Application_Error(object sender, EventArgs e)
{
    Application["Exception"] = Server.GetLastError();
    if (Application["DoNotRedirectOnError"] != null && (bool)Application["DoNotRedirectOnError"] == true)
    {
        Server.Execute("ErrorPage.aspx");
        Application["DoNotRedirectOnError"] = false;
    }
    else
    {
        Response.Redirect("ErrorPage.aspx");
    }
}

This will still execute the page behind the scenes (logging the error etc) but shouldn't trigger the Session Start again.


keep the logic inside Session_Start as simple as possible and put a try catch so all exceptions from there will be handled. Use logging to log what happens in such catch block in case control flow gets into the catch (well you should log exceptions anyway in any single catch block of your application... :) ), but not re-throw anything from Session_Start.

0

精彩评论

暂无评论...
验证码 换一张
取 消