如何使用asp.net身份创建交易?

时间:2015-09-30 04:48:07

标签: c# asp.net-mvc asp.net-identity owin

我正在进行注册,我要求提供5件事:

全名,EMAILID,密码ContactNumber,性别

现在使用寄存器方法存储的emailid和密码,并在以下两个链接中给出:

public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

            using var context = new MyEntities())
            {
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var DataModel = new UserMaster();
                        DataModel.Gender = model.Gender.ToString();
                        DataModel.Name = string.Empty;
                        var result = await UserManager.CreateAsync(user, model.Password);//Doing entry in AspnetUser even if transaction fails
                        if (result.Succeeded)
                        {
                            await this.UserManager.AddToRoleAsync(user.Id, model.Role.ToString());
                            this.AddUser(DataModel, context);
                            transaction.Commit();
                            return View("DisplayEmail");
                        }
                        AddErrors(result);
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        return null;
                    }

                }
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

public int AddUser(UserMaster _addUser, MyEntities _context)
    {
        _context.UserMaster.Add(_addUser);           
        _context.SaveChanges();
        return 0;
    }

现在有以下两行:

var result = await UserManager.CreateAsync(user, model.Password);//entry is done in AspnetUsers table.
await this.UserManager.AddToRoleAsync(user.Id, model.Role.ToString());//entry is done is Aspnetuserrole table

现在这个全名,contactno,性别我在另一个 UserMaster 的表中。

因此,当我将提交我的注册表单时,我将在 UserMaster和AspnetUsers,AspnetUserinrole表中保存此详细信息

但是考虑在UserMaster中保存记录时是否出现任何问题,那么我也不想在Aspnetuser和Aspnetuserinrole中保存条目。

我想创建一个事务,如果在任何表中保存任何记录时出现任何问题,我会回滚,但不应在AspnetUser,AspnetUserinRole和userMaster中进行任何输入。

只有在这3个表中保存记录没有问题时才能成功保存记录,否则事务应该是角色回来。

我正在使用Microsoft.AspNet.Identity进行登录,注册,角色管理等,并遵循本教程

http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset

http://www.asp.net/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity

但是,等待UserManager.CreateAsync和UserManager.AddToRoleAsync方法是内置的方法,我将如何将它与实体框架同步。

那么有人可以指导我如何创建这样的交易或任何可以解决这个问题的事情吗?

IdentityConfig

public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = 
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }

    // Configure the application sign-in manager which is used in this application.
    public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }

        public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
        }

        public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
        }
    }

2 个答案:

答案 0 :(得分:9)

您不应该创建新的数据库上下文,而是使用现有的上下文。

var context = Request.GetOwinContext().Get<MyEntities>()

如果您使用默认实现,则会根据请求创建。

app.CreatePerOwinContext(ApplicationDbContext.Create);

<强>更新

好的,既然您使用了两种不同的上下文,那么您的代码将如下所示:

public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

        var appDbContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
        using( var context = new MyEntities())
        using (var transaction = appDbContext.Database.BeginTransaction())
        {
            try
            {
                var DataModel = new UserMaster();
                DataModel.Gender = model.Gender.ToString();
                DataModel.Name = string.Empty;

                // Doing entry in AspnetUser even if transaction fails
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await this.UserManager.AddToRoleAsync(user.Id, model.Role.ToString());
                    this.AddUser(DataModel, context);
                    transaction.Commit();
                    return View("DisplayEmail");
                }
                AddErrors(result);
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return null;
            }
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

public int AddUser(UserMaster _addUser, MyEntities _context)
{
    _context.UserMaster.Add(_addUser);
    _context.SaveChanges();
    return 0;
}

此处,appDbContextUserManager使用的内容相同。

答案 1 :(得分:2)

您可以使用TransactionScope类来解决它:

using (TransactionScope scope = new TransactionScope())
{
    var result = await UserManager.CreateAsync(user, model.Password);
    if (result.Succeeded)
    {
        await this.UserManager.AddToRoleAsync(user.Id, model.Role.ToString());
        string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
        return View("DisplayEmail");
    }
    scope.Complete();
}

因此,两个操作都将在一个事务中完成,如果方法Comlete没有调用,则两个操作都将被取消(roolback)。

如果您只想用EF解决它(没有TransactionScope),您需要重构代码。我不知道类UserManager和方法CreateAsyncAddToRoleAsync的实现,但我猜他们为每个操作创建了新的DBContext。因此,首先,对于所有事务操作,您需要一个DBContext(用于EF解决方案)。如果您添加此方法,我将根据EF解决方案修改我的答案。