AspNet.Identity自定义用户和自定义角色应该很简单;我错过了什么?

时间:2014-03-28 18:57:23

标签: asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-6 asp.net-identity

使用http://www.asp.net/identity中的示例我已经走到了这一步。 RoleManager完美无瑕地工作,我对UserManager也一视同仁。我认为一切都是正确的,但我似乎无法在控制器中正确地创建UserManager。怎么了?有一次,我成功地让UserManager工作,但得到EntityValidationError说'#34; ID是必需的"创建此问题UserManager.Create(user, password) thowing EntityValidationError saying Id is required?

中发布的UserManager.Create(user, password);新用户时

所以经过一段时间的点击和错过,我已经创建了如下所示的所有内容,但我在new ApplicationUserManager(new ApplicationUserStore(new MyAppDb()))上遇到编译时错误,"&#34的最佳重载方法匹配39; MyApp.Models.ApplicationUserManager.ApplicationUserManager(Microsoft.AspNet.Identity.IUserStore)'有一些无效的论点"在尝试创建' UserManager'在我的控制器中:

这是控制器:

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; }
...
}

以下是模型:

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)
        {
        }

    }
}

更新:我可以通过更改此内容来创建UserManager,从而消除错误:

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 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 };
    }
}

注意我刚刚添加了, string,但它会将错误&#34;最佳重载方法匹配为&#34; Microsoft.AspNet.Identity.UserMaager.UserManager(Microsoft.AspNet.Identity.IUserStore) )&#39;有一些无效的论点&#34;在base(store)

更新2:我改变了这个:

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

到此:

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

请注意' string中的public class ApplicationUserManager : UserManager<ApplicationUser, string>。但现在,猜猜怎么着?你猜对了 - 回到这个问题:UserManager.Create(user, password) thowing EntityValidationError saying Id is required?

我缺少什么?

1 个答案:

答案 0 :(得分:6)

试试这种方式。我有同样的问题,你需要提供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);
    }