本文介绍了AspNet.Identity自定义用户和自定义角色应该很简单;我失踪了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用的示例我已经得到了远。 RoleManager 完美无缺,我将 UserManager 相同。我认为一切都是正确的,但我似乎无法在控制器中正确添加一个 UserManager 。哪里不对?有一点,我成功地获得了 UserManager 的工作,但是获得了一个 EntityValidationError ,说需要ID,当使用 UserManager.Create(user,password); 创建一个新用户,发布在此问题



所以经过一段时间的命中和错过,我已经创建了以下所有内容,但是在新的ApplicationUserManager(新的ApplicationUserStore(新的MyAppDb()))上得到编译时错误。说:在我的控制器中尝试创建UserManager时,MyApp.Models.ApplicationUserManager.ApplicationUserManager(Microsoft.AspNet.Identity.IUserStore)中的最佳重载方法匹配有一些无效参数:



这是控制器:

 命名空间MyApp.Controllers 
{
[授权]
public class AccountController:BaseController
{
public AccountController )
:this(new ApplicationUserManager(new ApplicationUserStore(new MyAppDb()))
{
}

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

public ApplicationUserManager UserManager {get;私人集合}
...
}

这是模型:

 命名空间MyApp.Models 
{
public class ApplicationUser:IdentityUser< string,ApplicationUserLogin,ApplicationUserRole,ApplicationUserClaim>
{
[必需]
[StringLength(50)]
public string FirstName {get;组;

[必需]
[StringLength(50)]
public string LastName {get;组; }


public async任务< ClaimsIdentity> GenerateUserIdentityAsync(UserManager< ApplicationUser> manager)
{
//请注意,authenticationType必须与CookieAuthenticationOptions.AuthenticationType
中定义的那个匹配。var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
//在此添加自定义用户声明
return userIdentity;
}
}

public class ApplicationUserLogin:IdentityUserLogin< string>
{
}

public class ApplicationUserClaim:IdentityUserClaim< string>
{
}

public class ApplicationUserRole:IdentityUserRole< string>
{
}

public class ApplicationRole:IdentityRole< string,ApplicationUserRole>
{
[必需]
[StringLength(50)]
public string ProperName {get;组;

[必需]
public string说明{get;组; }
}


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 );
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任务CreateAsync(ApplicationUser用户)
{
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 );
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};
}
}

注意我刚添加字符串,但是它会将错误最佳重载方法匹配Microsoft.AspNet.Identity.UserMaager.UserManager(Microsoft.AspNet.Identity.IUserStore)'在 base(store)



更新2:我更改了:

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



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

请注意<$ c中的'字符串 $ c> public class ApplicationUserManager:UserManager< Appl icationUser,string> 。但现在,猜猜是什么?你猜到了 - 回到这个问题:



我缺少什么? / p>

解决方案

尝试这种方式。我有同样的问题,你需要提供id。

  // 
// POST:/ Account / Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async任务< ActionResult>注册(RegisterViewModel模型)
{
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);
}



}

//如果我们得到这么远的东西,失败了,重新显示窗体
return View(模型);
}


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?

解决方案

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

这篇关于AspNet.Identity自定义用户和自定义角色应该很简单;我失踪了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 07:15