我一直在爲這一個難住。用戶在執行回發時將隨機獲得空引用異常。在我看來,問題來自模型聯編程序,可能是解析屬性的順序。只是想看看有沒有人有任何意見?我沒有能夠複製將調試,只發生在生產隨機回發。Postback上出現的隨機NullReferenceException
相當簡單視圖模型:
public class ViewModel
{
public Load Load { get; set; }
public bool ReadOnly
{
get
{
return this.GetStatus(Load.Date);
}
}
public Load PrevLoad { get; set; }
private bool GetStatus(DateTime? date)
{
if (date != null)
{
if (date.Value.DayOfWeek == DayOfWeek.Monday)
date = date.Value.AddDays(-2);
return ((DateTime.Now.AbsoluteEnd() - date.Value.AbsoluteEnd()).TotalHours) <= -24 ? false : true;
}
else
return true;
}
}
堆棧跟蹤(注意我x'd歇業敏感的命名空間):
System.Reflection.TargetInvocationException: Property accessor 'ReadOnly' on object
'XXX.XX.XXX.XXX.ViewModel' threw the following exception:'Object reference not set to an instance of an object.' ---> System.NullReferenceException: Object reference not set to an instance of an object.
at XXX.XX.XXX.ViewModels.ViewModel.get_ReadOnly()
--- End of inner exception stack trace ---
at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)
at System.Web.Mvc.DataAnnotationsModelValidator.<Validate>d__15.MoveNext()
at System.Web.Mvc.ModelValidator.CompositeModelValidator.<Validate>d__1.MoveNext()
at System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass1e.<BeginInvokeAction>b__16(AsyncCallback asyncCallback, Object asyncState)
當我傳遞null this.GetStatus我得到一個不同的例外;所以我知道那是不可能的。
您是否認爲這是拋出異常,因爲在modelBinding發生時以及嘗試訪問this.GetSatus時,它在技術上不是ViewModel的實例?這仍然無法解釋爲什麼有時會出現這種情況。
根據例外'Load'爲'null'。 「Load」在哪裏填充?如果模型聯編程序沒有收到足夠的信息來構造'Load'屬性,那麼引用類型的默認值爲'null'。視圖模型不會在內部實例化'Load'或者檢查它是否爲'null',所以這個異常是非常現實的可能性。 – David 2014-09-18 19:42:10
你從哪裏得到堆棧跟蹤?此外,我加載不應該傳回給控制器,因爲在Load中沒有呈現隱藏在視圖中的任何屬性。 ReadOnly僅用於使頁面上的某些元素處於禁用狀態。回發時不需要。 – Botonomous 2014-09-18 19:44:40
堆棧跟蹤的第一行:'ViewModel.get_ReadOnly()'該方法只有一行:'return this.GetStatus(Load.Date);'假設'this'不能爲'null','Load '一定是。看起來,框架的模型驗證試圖讀取視圖模型中的屬性,但是如果'Load'爲'null',任何嘗試讀取它的屬性都會引發異常。 – David 2014-09-18 19:47:44