当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net mvc - Logging in with MVC Identity

问题描述:

I am using Identity to handle my user, and usually in the Register function both the Username and Email is set equal to the Email in the RegisterViewModel

In my view I added an extra input, called username, and I added it to the model.

So in the code below you can see me change the value of Username from the email value in the model, to my new username value in the model

// POST: /Account/Register

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task<ActionResult> Register(RegisterViewModel model)

{

if (ModelState.IsValid)

{

var user = new ApplicationUser { UserName = model.Username, Email = model.Email };

var result = await UserManager.CreateAsync(user, model.Password);

if (result.Succeeded)

{

await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

return RedirectToAction("Index", "Home");

}

AddErrors(result);

}

// If we got this far, something failed, redisplay form

return View(model);

}

And it works great, it's saved as it should be in the database etc.

BUT

After I log off, and try to log in again, I am not able to log in.

And the thing is, if I change back so that username is equal to the email like it normally is, then it works.

But shouldn't I be able to log in, because the email field in the identity database is still the email the user entered, so why does changing the username affect this?

And how can it be fixed? Thank you.

LOGIN CODE

// POST: /Account/Login

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)

{

if (!ModelState.IsValid)

{

return View(model);

}

// 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(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, RememberMe = model.RememberMe });

case SignInStatus.Failure:

default:

ModelState.AddModelError("", "Invalid login attempt.");

return View(model);

}

}

分享给朋友:
您可能感兴趣的文章:
随机阅读: