2014-04-16 118 views
-1

我在忘記密碼部分有NullReferenceException錯誤。我的錯誤在哪裏,我該如何解決?這裏是我的代碼:ASP.NET MVC中的NullReferenceException錯誤

我的控制器:

 public ActionResult ForGotPasswordSent(ForGotModel forgetModel) 
      { 
       User user = _userService.GetUserByEmail(forgetModel.Email); 
       if (user.IsActive) 
       { 
        var objEmail = new EmailHelper(); 
        Message msg = new Message(); 
        msg.SuccessMessage = "You have sent the mail,Please verify that"; 
        msg.IsSuccess = true; 
        string strBody = "Thanks for using the forgot password function.You need to set new password to your account, please click here to proceed"; 
        bool result = objEmail.SendMail("[email protected]", "[email protected]", "", "Activate Your Account", strBody, true); 
        if (result) 
         return View("Activation", msg); 
        else 
         return View("Activation"); 
       } 
       else 
       { 

        this.ModelState.AddModelError("", "You have to activate your account"); 
        return View("Activation"); 
       } 
      } 

我的用戶等級:

public class User : IPrincipal 
    { 

     public int Id { get; set; } 

     [Required(ErrorMessage = "Kullanıcı adı girilmesi zorunludur.")] 
     [Display(Name = "Kullanıcı Adı")] 
     public string Username { get; set; } 

     [Required] 
     [DataType(DataType.EmailAddress)] 
     [Display(Name = "Email address")] 
     public string Email { get; set; } 


     [Required(ErrorMessage = "Password Required")] 
     public string Password { get; set; } 

     [DataType(DataType.Password)] 
     [Display(Name = "Confirm password")] 
     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
     public string ConfirmPassword { get; set; } 

     public bool IsActive { get; set; } 
     public bool IsAdmin { get; set; } 
     public bool IsDeleted { get; set; } 
     public DateTime? CreatedDate { get; set; } 
     public DateTime? ModifiedDate { get; set; } 

我ForgotModel

public class ForGotModel 
{ 
    [Required] 
    [Display(Name = "Email")] 
    public string Email { get; set; } 

} 

_userService.GetUserByEmail方法:

public User GetUserByEmail(string email) 
     { 
      var user = _userRepository.Get(x => x.Email == email); 

      return user; 
     } 
+3

你確認你的'User'對象不是null嗎? –

回答

2

您可能會希望在檢查IsActive屬性之前向用戶添加空檢查。試試這個:

if (user != null && user.IsActive) 
+0

在這種情況下,如果對UserRepository的調用沒有返回匹配該電子郵件的記錄,然後嘗試訪問該空對象上的屬性(user.IsActive),則會引發NullReferenceException。 – MDiesel

1

GetUserByEmail可能會在沒有用戶被發現時返回null。在檢查user.IsActive之前,確認您的用戶對象不爲空。