我正在使用MVC3,C#,Razor,.NET4
我在模型构造函数中使用了会话变量。有时它可以为null,这主要是由于AppPool的回收。我需要捕获会话的“空”错误,并理想地重定向到另一个操作,即错误/索引。但是我在模型中,我不确定是否可以重定向到模型类之外。
我的代码:
try
{
intOrderId = (Int32) System.Web.HttpContext.Current.Session["OrderId"];
intSupplierId = (Int32) System.Web.HttpContext.Current.Session["SupplierId"];
}
catch (Exception e)
{
// Redirect to Error/Index ?????
}
我有一种感觉,我可能必须在模型中设置一个属性以突出显示错误,然后让控制器的操作对此进行检查并采取相应的措施,但是我有很多调用此模型的操作,所以我不想这样做这。我宁愿在一处对这个错误做出反应。
在此先感谢您的任何帮助。
与其使用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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句