Vag*_*gue 3 entity-framework-core asp.net-core-mvc asp.net-identity-3 asp.net-core
我们正在尝试在ASP.Net 5项目中使用Microsoft帐户身份验证.我们不需要本地身份验证,也不需要用户名.
在用于Web应用程序的ASP.Net 5模板中,在使用外部提供程序登录后,控件将返回到ExternalLoginCallbackAccountController中.
如果用户未在本地注册,ExternalLoginCallback则将用户返回到注册屏幕.我试图修改ExternalLoginCallback为自动注册新用户,如下所示.
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
//ViewData["ReturnUrl"] = returnUrl;
//ViewData["LoginProvider"] = info.LoginProvider;
//var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
//return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
// The user has not previously logged in with an external provider. Create a new user.
CreateUser(info);
return RedirectToLocal(returnUrl);
}
}
Run Code Online (Sandbox Code Playgroud)
CreateUser实现从ExternalLoginConfirmationWeb应用程序的ASP.Net 5模板中显示的复制代码.
private async void CreateUser(ExternalLoginInfo info)
{
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
var user = new ApplicationUser { UserName = email, Email = email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
}
}
AddErrors(result);
}
Run Code Online (Sandbox Code Playgroud)
线路上出现错误
var result = await _userManager.CreateAsync(user);
Run Code Online (Sandbox Code Playgroud)
错误是
System.ObjectDisposedException was unhandled Message: An unhandled exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll. Additional information: Cannot access a disposed object.
Run Code Online (Sandbox Code Playgroud)
我已经重新启动了我的机器,以防它只是"其中一件事",但错误再次发生.
使用的async void方法是很少一个好主意,是引入怪异的竞争条件像您遇到的一个最好的方式,因为你的CreateUser方法不返回的任务,它不能被期待已久ExternalLoginCallback,并请求之前完成CreateUser有执行数据库操作的时间(当请求完成时,DI系统调用Dispose范围内的依赖关系,如您的EF上下文).
更新您的CreateUser方法以返回Task并等待它ExternalLoginCallback,它应该工作:
await CreateUser(info);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1608 次 |
| 最近记录: |