c# - 如何处理错误信息: Session state is not available in this context

标签 c# asp.net

我正在尝试创建一个错误消息页面以在发生异常时显示异常,并且错误消息页面上有一个返回按钮可以返回到导致异常发生的上一个页面。

这是用于重定向错误页面的代码。

protected void btnAssign_Click(object sender, EventArgs e)
{
    try
    {
        SqlDataSource3.Insert();
    }
    catch (Exception ex)
    {
        Session["Exception"] = ex;
        Response.Redirect("~/ErrorMessage.aspx", false);
    } 
}

这是我的 global.asax 文件的代码

void Application_Error(object sender, EventArgs e) 
{ 
    // Code that runs when an unhandled error occurs
    Exception ex = Server.GetLastError().InnerException;
    Session["Exception"] = ex;
    Response.Redirect("~/ErrorMessage.aspx");
}

这里是errorMessage页面的代码。

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Exception ex = (Exception)Session["Exception"];
            Session.Remove("Exception");
            Literal1.Text = "<p style='color:blue'><b>An unrecoverable error has occurred:</b></p><br /><p style='color:red'>" + ex.Message + "</p>";
        }  
    }
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/IncidentAssignment.aspx");
    }

当我单击分配按钮时,它会打开错误消息页面并显示异常,但是当我单击返回按钮时,程序崩溃并指向 global.asax 文件并显示 session 状态在此上下文中不可用,如图所示在吹。 enter image description here

我不明白为什么 session["exception"] 为空。如果有人回答我的问题,将不胜感激。谢谢。

最佳答案

您正在尝试访问应用程序错误事件中的 session 状态,这可能是您的 session 对象未被初始化。错误可能会在您的应用程序的其他位置引发,因为它涉及整个应用程序。

这通常发生在您的错误抛出是在您的应用程序初始阶段,因此 session 对象未被初始化。例如。在 Begin_Request 事件中。

您可以在访问 session 对象之前进行空检查。

if (HttpContext.Current.Session != null) { //do your stuff}

关于c# - 如何处理错误信息: Session state is not available in this context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15016973/

相关文章:

c# - Swagger 的服务堆栈不起作用

c# - NET4 功能 : should casting generic IEnumerable<T> to IEnumerable<MoreSpecificT> be possible?

c# - Page head 元素中的尖括号

asp.net - 仅在第二次单击时调用事件处理程序

asp.net - 如何在asp.net中检测新的Microsoft浏览器 "Edge"

c# - asp.net mvc中如何判断session值为null或session key不存在 - 5

c# - 跳过WebForm中SqlDataSource中sql参数的设置值

c# - 是否可以在 iCal.net 上使用 UTC 偏移量而不是时区名称?

c# - AWS API 网关签名

c# - Linq 无法隐式转换类型