问题
I am using the custom errors attribute in the web.config to handle custom errors
Like this:
<customErrors mode="On" defaultRedirect="~/Error.aspx" redirectMode="ResponseRewrite" />
After an error is thrown, the page is redirected to the error page, but when I access the session in the error page it is null.
The reason I use ResponseRewrite
and not ResponseRedirect
is because I pass the Exception id
through Items using elmah.
I even tried to create new empty asp.net website and it still happens.
I've seen some similar questions but without an answer.
回答1:
I reproduced the problem, but I can't understand why this happens. In the Application_Error
handler I can access the Session variable, but when the page loads it becomes null
.
I found a workaround here that solves the problem. You need to remove the redirectMode
from your web.config and manually do the Server.Transfer
when you get an error. So this is the web.config:
<customErrors mode="On" defaultRedirect="~/Error.aspx"/>
And add this to the Global.asax.cs
file:
void Application_Error(object sender, EventArgs e)
{
if(Context.IsCustomErrorEnabled)
{
Server.Transfer("~/Error.aspx");
}
}
To specify different error pages depending on the error, you can access the error code like this:
HttpException httpException = (HttpException) Server.GetLastError();
int httpCode = httpException.GetHttpCode();
switch (httpCode)
{
case 500: Server.Transfer("~/Pages/Error.aspx");break;
case 404: Server.Transfer("~/Pages/PageNotFound.aspx");break;
default: Server.Transfer("~/Pages/Error.aspx");break;
}
来源:https://stackoverflow.com/questions/16397453/session-is-null-after-responserewrite