AspNet.Identity Custom User and Custom Role should

2019-05-13 00:25发布

问题:

Using examples from http://www.asp.net/identity I've gotten this far. The RoleManager works flawlessly and I treat the UserManager the same. I think everything is correct, but I can't seem to new up a UserManager correctly in a controller. What is wrong? At one point, I was successfully getting the UserManager to work but was getting an EntityValidationError saying "Id is required" when creating a new user with UserManager.Create(user, password); as posted in this question UserManager.Create(user, password) thowing EntityValidationError saying Id is required?

So after some time of hit and miss, I've created everything like the following but am getting a compile-time error on new ApplicationUserManager(new ApplicationUserStore(new MyAppDb())) saying, "The best overloaded method match for 'MyApp.Models.ApplicationUserManager.ApplicationUserManager(Microsoft.AspNet.Identity.IUserStore)' has some invalid arguments" when trying to create the 'UserManager' in my controller:

Here is the controller:

namespace MyApp.Controllers
{
    [Authorize]
    public class AccountController : BaseController
    {
        public AccountController()
            : this(new ApplicationUserManager(new ApplicationUserStore(new MyAppDb())))
        {
        }

        public AccountController(ApplicationUserManager userManager)
        {
            UserManager = userManager;
        }

        public ApplicationUserManager UserManager { get; private set; }
...
}

Here is the model:

namespace MyApp.Models
{
    public class ApplicationUser : IdentityUser<string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
        [Required]
        [StringLength(50)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(50)]
        public string LastName { get; set; }


        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationUserLogin : IdentityUserLogin<string>
    {
    }

    public class ApplicationUserClaim : IdentityUserClaim<string>
    {
    }

    public class ApplicationUserRole : IdentityUserRole<string>
    {
    }

    public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
    {
        [Required]
        [StringLength(50)]
        public string ProperName { get; set; }

        [Required]
        public string Description { get; set; }
    }


    public class MyAppDb : IdentityDbContext<ApplicationUser, ApplicationRole, string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
        public MyAppDb()
            : base("MyAppDb")
        {
        }
    }


    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
            this.PasswordValidator = (IIdentityValidator<string>)new MinimumLengthValidator(8);
            this.UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true };
        }

    }

    public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
        public ApplicationUserStore(MyAppDb context)
            : base(context)
        {
        }

        public override async Task CreateAsync(ApplicationUser user)
        {
            await base.CreateAsync(user);

        }
    }


    public class ApplicationRoleStore : RoleStore<ApplicationRole, string, ApplicationUserRole>
    {
        public ApplicationRoleStore(MyAppDb context)
            : base(context)
        {
        }
    }

    public class ApplicationRoleManager : RoleManager<ApplicationRole>
    {
        public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store)
            : base(store)
        {
        }

    }
}

UPDATE: I can get the error to go away on the creation of the UserManager by changing this:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
        this.PasswordValidator = (IIdentityValidator<string>)new MinimumLengthValidator(8);
        this.UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true };
    }
}

to this:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser, string> store)
        : base(store)
    {
        this.PasswordValidator = (IIdentityValidator<string>)new MinimumLengthValidator(8);
        this.UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true };
    }
}

notice I just added , string, but it then puts the error "The best overloaded method match for "Microsoft.AspNet.Identity.UserMaager.UserManager(Microsoft.AspNet.Identity.IUserStore)' has some invalid arguments" on base(store).

UPDATE 2: I changed this:

public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser, string> store)
        ...
    }

to this:

public class ApplicationUserManager : UserManager<ApplicationUser, string>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser, string> store)
        ...
    }

Notice the ' string in public class ApplicationUserManager : UserManager<ApplicationUser, string>. But now, guess what? You guessed it--back to this issue: UserManager.Create(user, password) thowing EntityValidationError saying Id is required?

What am I missing?

回答1:

Try this way. I had the same issue, you need to provide the id.

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { 
                UserName = model.UserName,
                Id = Guid.NewGuid().ToString(),
                Created = DateTime.Now,
                LastLogin = null
            };

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }



        }

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