如何处理MVC ASP.NET中“Model”类中的错误,与null会话变量有关

时间:2014-04-16 00:40:31

标签: asp.net-mvc asp.net-mvc-3

我正在使用MVC3,C#,Razor,.NET4

我在我的Model构造函数中使用会话变量。有时它可能为null,主要是由于AppPool的回收。我需要捕获会话的“null”错误,并理想地重定向到另一个操作,即错误/索引。但是我在模型中,我不确定是否可以重定向模型类。

我的代码:

        try
        {
            intOrderId = (Int32) System.Web.HttpContext.Current.Session["OrderId"];
            intSupplierId = (Int32) System.Web.HttpContext.Current.Session["SupplierId"];
        }
        catch (Exception e)
        {
          // Redirect to Error/Index ?????
        }

我有一种感觉,我可能必须在模型中设置一个属性来突出显示错误,然后让控制器的操作检查这个并采取相应的行动,但是我有很多动作调用这个模型,所以我不是想要这样做。我宁愿在一个地方对这个错误做出反应。

非常感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:2)

不是使用try / catch来处理空值,为什么不在读之前检查?

if(System.Web.HttpContext.Current.Session["OrderId"] != null)
   && System.Web.HttpContext.Current.Session["SupplierId"] != null)
{
    intOrderId = (Int32) System.Web.HttpContext.Current.Session["OrderId"];
    intSupplierId = (Int32) System.Web.HttpContext.Current.Session["SupplierId"];
}
else
{
   //Throw an exception that the controller can catch: NullReferenceException or InvalidCastException.
   //Or return a specific value to indicate that an error occured
}