2014-01-06 64 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