UserManager.FindByEmail()返回Null

时间:2015-05-18 14:56:15

标签: asp.net-mvc

我正在尝试在AspNet.Identity中为MVC5实现基于电子邮件地址的用户名。只要系统上有注册的电子邮件/用户名,我的应用程序就可以找到。

我刚刚发现,如果用户不存在并尝试登录,则会在第72行引发异常。

  

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

     

来源错误:
     第71行://添加此项以检查电子邮件是否已确认      第72行:var userid = UserManager.FindByEmail(model.Email).Id;

这是我的代码。

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        //Add this to check if the email was confirmed. 
        var userid = UserManager.FindByEmail(model.Email).Id; 
        // **Line 72. 'userid' is empty.**

        // Here is my attempt but doesn't do anything. 
        if (string.IsNullOrEmpty(userid)) {
            ModelState.AddModelError("","You are not registered!");
        }

        if (!UserManager.IsEmailConfirmed(userid))
        {
            ModelState.AddModelError("", "E-mail address has not been confirmed.");
            return View(model);
        } 
    }  
    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);  
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}

谢谢!

2 个答案:

答案 0 :(得分:0)

我添加了下面的代码并且它有效但我还是不明白FindByNameAsyn()方法实际上是如何工作而不是FindByName()?也  有一个更好的方法吗?谢谢!

// Code that works. 

var user = await UserManager.FindByNameAsync(model.Email);

if (user == null)
{
    ModelState.AddModelError("", "Invalid login attempt.");
    return View(model);
}

答案 1 :(得分:0)

我尝试了以下代码并为我工作:

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        string userName = "";   // to be used as arg to PasswordSignInAsync

        // you'd better declare the appropriate Type.
        // using "var" doesn't work here - I don't know why...
        ApplicationUser user = await UserManager.FindByEmailAsync(model.UserName);

        if (user != null)
        {
            // found an existing user having the given Email
            // so let's get it's UserName to test SignIn
            userName = user.UserName;
            // just for debugging - check your AspNetUser table 
            // ModelState.AddModelError("", userName + " ID = " + user.Id.ToString());
        }
        else
        {
            // Hum... no email found - perhaps the user is really trying the UserName
            // Perhaps Email != UserName  
            // It's interesting to give the user the option to use Email or UserName
            // to get authenticated.
            // Let's play, then! 
            userName = model.UserName;
        }

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(userName, model.Password, 
                                model.RememberMe, shouldLockout: true);

        // from here on, it's the scaffolded code...

        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

希望它有用,即使在那段时间之后。

如果您的问题得到解决,请告诉我们。 问候。