ASP.NET身份确认后如何自动登录

How to perform an automatic login after confirming the account with ASP.NET Identity

我目前正在开发一个 MVC5 网络应用程序,使用 ASP.NET Identity 2 进行帐户控制,我遇到的具体问题是自动登录用户 after 电子邮件确认。

所以流程如下:

  1. 用户点击注册link
  2. 输入电子邮件(用户名)/密码,点击注册
  3. 一封电子邮件发送到给定的地址 "please confirmaccount" URL
  4. 用户单击 link,确认电子邮件地址并自动登录

控制器上的确认电子邮件操作如下所示:

[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
   // If userId or code is empty, show an error or redirect
   if (userId == null || code == null)
   {
     return View("Error");
   }

   // Attempt to confirm the email address
   var confirmEmailResult = await UserManager.ConfirmEmailAsync(userId, code);

   // Retrieve the user (ApplicationUser)
   var user = await UserManager.Users.FirstOrDefaultAsync(u => u.Id == userId);
   if (user == null)
   {
     // If the user doesn't exist, redirect home
     return RedirectToAction("Index", "Home");
   }

   // If the confirmation succeeded, sign in the user and redirect to this profile page
   if (confirmEmailResult.Succeeded)
   {
     await SignInManager.SignInAsync(user, false, false);

     var url = Url.Action("Profile", "User");
     return RedirectToLocal(url);
   }

   // In all other cases, redirect to an error page
   return View("Error");
}

奇怪的是,我可以确认电子邮件 登录用户,出于某种原因,如果我同时执行这两项操作... 它不起作用。具体来说,我在这一行收到 TimeOutException:

await SignInManager.SignInAsync(user, false, false);

这是非常令人难以置信的,因为我知道数据库和应用程序服务器不是问题。

我是不是用错了方法...?

提前致谢!

好的,答案已经找到,问题如下,每个请求都设置了级别Read Commited的事务。这导致第二次更改(创建)被第一次更改(电子邮件确认)阻止,导致超时...

async Task IRunBeforeEachRequest.Execute()
{
  _HttpContext.Items[IdentityContextTransactionKey] = _IdentityContext.Database.BeginTransaction(IsolationLevel.ReadCommitted);
  _HttpContext.Items[TravellersContextTransactionKey] = _TravellersContext.Database.BeginTransaction(IsolationLevel.ReadCommitted);
}

再次感谢您的帮助!