1

我正在开发一个基于 API 的网站,客户端正在.Net MVC 中开发。对于异常处理,我正在使用

 public void Application_Error(object sender, EventArgs e)
        {
            string action = "Index";
            Exception exception = Server.GetLastError();
            Response.Clear();

            HttpException httpException = exception as HttpException;

            if (httpException != null)
            {


                switch (httpException.GetHttpCode())
                {
                    case 404:
                        // page not found
                        action = "Error404";
                        break;
                    default:
                        action = "Index";
                        break;
                }

                // clear error on server
                Server.ClearError();
            }
            Response.Redirect(String.Format("/error/{0}", action));
        }

因此对于控制器的 try catch 抛出的任何异常,页面都会重定向到错误页面。

现在我希望当会话过期时它应该重定向到登录页面,我该怎么做?

现在发生的事情是,在会话到期后,当我尝试访问会话值时,它会抛出异常“ object reference not set to an instance of object。” 然后它重定向到默认错误页面。

4

1 回答 1

3

我认为您无法从通用异常处理程序内部执行此操作,因为-正如您所说-缺少会话变量只会抛出NullReferenceException. 从控制器对会话变量执行空检查:

Public ActionResult MyAction ()
{
    if (Session["myVariable"] == null)
    {
        RedirectToAction("SessionTimeOut", "Error");
    }

    ...

}

如果您的会话变量应该始终存在,除非会话已过期,您可以尝试覆盖OnActionExecuting控制器的方法并在那里执行您的空检查。要为多个控制器执行此操作,请定义 a BaseController,覆盖其OnActionExecuting方法,然后在其他控制器中继承此方法。

于 2012-11-22T07:00:55.883 回答