2014-01-06 36 views
2

在我的一個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行提出異常,我不明白如何才能給出它是一個簡單的函數調用。

任何幫助將不勝感激。提前致謝。

+0

在你的'else if'你確定'user'或'user.role'不是null嗎? –

+2

@BitsEvolved:你可以調試這段代碼並打破異常嗎?或者得到一個可以幫助你診斷的轉儲文件? –

+1

@DROPtableusers,'user',至少在'else if'條件下不會爲空,因爲'if'條件正在檢查這個條件。 –

回答

0

假設this.accountServices不能爲空,你的代碼對我來說看起來很好,所以我會建議異常實際上發生在其他地方(可能是由於內聯)。

查看this question瞭解有關在發佈模式下顯示正確行數的詳細信息。

+0

感謝您的建議,但我已經做出了這些改變(除非我錯過了一個步驟)。我會仔細檢查我的配置。 – BitsEvolved