c# – 与ASP.NET Identity UserManager的事务
作者:互联网
我正在尝试更新用户.
AppUserManager appUserManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
AppUser member = await appUserManager.FindByIdAsync(User.Identity.GetUserId());
member.HasScheduledChanges = true;
IdentityResult identityResult = appUserManager.Update(member);
如果后续调用Web API失败,我需要回滚对用户的任何更改.我知道交易,像这样:
using (var context = HttpContext.GetOwinContext().Get<EFDbContext>())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
// Changes
member.HasScheduledChanges = true;
// Would this be transactional?
IdentityResult identityResult = appUserManager.Update(member);
context.SaveChanges();
dbContextTransaction.Commit();
}
catch //(Exception ex)
{
// dbContextTransaction.Rollback(); no need to call this manually.
}
}
}
但是,在try块中使用AppUserManager进行的操作是否是事务性的?另外,他们使用相同的EFDbContext实例吗?换句话说,我不知道第二个代码示例开头的var context是否会被try块中的appUserManager“Update”方法调用使用.
此外,AppUserManager的创建方式如下:
public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
{
EFDbContext db = context.Get<EFDbContext>();
AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db));
// etc.
return manager;
}
解决方法:
示例中的EFDbContext是相同的 – 在这两种情况下,您都可以从OWIN上下文中解析它们,因此这不是问题.但是,Identity以存储无关的方式编写,这意味着存储机制可以由非SQL Server替换.这要求AppUserManager内部缺少事务.所以你需要创建自己的.
我经常在我的生产应用程序中使用var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)(仅使用更多架构):
using(var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
try
{
AppUserManager appUserManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
AppUser member = await appUserManager.FindByIdAsync(User.Identity.GetUserId());
member.HasScheduledChanges = true;
IdentityResult identityResult = appUserManager.Update(member);
scope.Complete();
}
catch (Exception ex)
{
scope.Dispose();
throw;
}
}
标签:c,asp-net,transactions,asp-net-identity,usermanager 来源: https://codeday.me/bug/20190717/1488168.html