Session is null after ResponseRewrite

[亡魂溺海] 提交于 2019-12-11 03:43:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!