在我的一個ASP.NET MVC網站上,偶爾會遇到一個NPE,我無法理解根本原因。我正在使用ELMAH來追蹤錯誤。空指針異常我在解決問題時遇到了問題
完整的堆棧跟蹤是在這裏(不多吧:
System.NullReferenceException: Object reference not set to an instance of an object.
at PG.Controllers.FooController.FooActionName(FooModel model) in
{REMOVED}\web\www\Controllers\FooController.cs:line 622
這裏的行622:
if(UserCanEditFoo(out result))
這裏的「UserCanEditFoo上市:
private bool UserCanEditFoo(out ActionResult result)
{
String email = User != null && User.Identity != null ? User.Identity.Name : String.Empty;
UserAccount user = String.IsNullOrEmpty(email) ? null : this.accountServices.GetUserAccount(email);
bool canEditFoo = false;
result = null;
// Don't know this user
if(user == null)
{
FormsAuthentication.SignOut();
Session.Abandon();
result = RedirectToAction(Routes.Actions.Index, Routes.Controllers.Home);
}
// Only admins and foo profile can edit foo
else if(user.Role != Types.UserRole.Admin && user.Role != Types.UserRole.Foo)
{
result = new HttpUnauthorizedResult("Oops! Only administrators and foo users can edit foo.");
}
else
{
result = null;
canEditFoo = true;
}
return canEditFoo;
}
我假設該異常實際上在「UserCanEditFoo」私有方法中引發,但我不明白爲什麼行號不是代表因此被搪塞。另一方面,如果真的在第622行提出異常,我不明白如何才能給出它是一個簡單的函數調用。
任何幫助將不勝感激。提前致謝。
在你的'else if'你確定'user'或'user.role'不是null嗎? –
@BitsEvolved:你可以調試這段代碼並打破異常嗎?或者得到一個可以幫助你診斷的轉儲文件? –
@DROPtableusers,'user',至少在'else if'條件下不會爲空,因爲'if'條件正在檢查這個條件。 –