【发布时间】:2017-11-14 09:51:11
【问题描述】:
几个月前,我创建了自己的 ASP.NET Identity 实现,重写了 UserStore 以使用 dapper 和自定义 sql 连接而不是 Entity Framework。当时效果很好。
现在我今天更新了所有的 nuget 包,从那以后我一直在与问题作斗争。主要是当我通过调用var result = await UserManager.CreateAsync(user, newAccount.Password);注册新用户时,它会创建用户并执行所有其他检查,但随后会抛出一个奇怪的错误,说Invalid operation. The connection is closed.
好像 UserManager.CreateAsync 有一个需要重写的新方法,但我完全不知道它可能是什么。
作为参考,以下是我的部分实现:
帐户管理员:
[Authorize]
public class AccountController : Controller
{
public UserManager<User> UserManager { get; private set; }
public UserTokenProvider UserTokenProvider { get; set; }
public AccountController() : this(new UserManager<User>(new UserStore(ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString)))
{
}
public AccountController(UserManager<User> userManager)
{
UserManager = userManager;
UserManager.PasswordHasher = new NoPasswordHasher();
}
...
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegistrationModel newAccount)
{
try
{
if (DbConfig.MaintenanceMode) return RedirectToAction("ComingSoon", "Home");
if (ModelState.IsValid)
{
var user = new User(newAccount);
var result = await UserManager.CreateAsync(user, newAccount.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
var userIn = await UserManager.FindByEmailAsync(newAccount.UserName);
if (!userIn.EmailConfirmed)
{
await SendValidationEmail(userIn);
return RedirectToAction("ConfirmationSent", new {userName = user.UserName});
}
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(newAccount);
}
catch (Exception ex)
{
var msg = ex.Message;
return View(newAccount);
}
}
用户商店:
public class UserStore : IUserStore<User>, IUserLoginStore<User>, IUserPasswordStore<User>, IUserSecurityStampStore<User>, IUserRoleStore<User>, IUserEmailStore<User>
{
private readonly string _dbConn;
public UserStore(string conn = null)
{
if (conn != null)
_dbConn = conn;
else
_dbConn = DbConfig.ConnectionString;
}
public void Dispose()
{
}
public virtual Task CreateAsync(User user)
{
using (var _conn = new SqlConnection(_dbConn))
{
if (_conn.State == ConnectionState.Closed) _conn.Open();
return _conn.ExecuteAsync("users_UserCreate",
new
{
@UserId = user.Id,
@UserName = user.UserName,
@PasswordHash = user.PasswordHash,
@SecurityStamp = user.SecurityStamp
}, commandType: CommandType.StoredProcedure);
}
}
... Remaining methods omitted for brevity ...
您会注意到 UserStore.CreateAsync() 函数具有if (_conn.State == ConnectionState.Closed) _conn.Open();,因为这是多个线程关于连接关闭错误的建议。即使没有这一行,查询也能正常工作并正确地将新用户插入数据库。
错误来自 UserManager.CreateAsync() 调用 UserStore.CreateAsync() 之后的某个地方。
知道缺少什么吗?
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-identity dapper