我使用 ASP.NET 身份,当用户想要注册时收到此错误:
值不能为空。\r参数名称: 管理器。
这是我的注册操作代码:
public virtual ActionResult Register(string nm, string em, string ps)
{
var redirectUrlPanel = new UrlHelper(Request.RequestContext).Action("Index", "HomeUsers", new { area = "Users" });
var redirectUrlAuction = new UrlHelper(Request.RequestContext).Action("Auction", "Default", new { area = "" });
if (ModelState.IsValid)
{
try
{
var user = new Q_Users();
user.UserName = nm;
user.Email = em;
user.SecurityStamp = Guid.NewGuid().ToString();
var adminresult = UserManager.Create(user, ps);
//Add User Admin to Role Admin
if (adminresult.Succeeded)
{
//Find Role Admin
var role = RoleManager.FindByName("Admin");
var result = UserManager.AddToRole(user.Id, role.Name);
if (result.Succeeded)
{
return Json(new { OK = "1", UrlPanel = redirectUrlPanel, UrlAuction = redirectUrlAuction });
}
}
else
{
return Json(new { OK = "0", UrlPanel = redirectUrlPanel, UrlAuction = redirectUrlAuction });
}
}
catch (Exception ex) { }
return Json(new { OK = "0", UrlPanel = redirectUrlPanel, UrlAuction = redirectUrlAuction });
}
else
{
return Json(new { OK = "0", UrlPanel = redirectUrlPanel, UrlAuction = redirectUrlAuction });
}
}
而这一行中的错误:var adminresult = UserManager.Create(user, ps);
您收到错误,因为角色管理器未初始化
要解决此问题,请按照以下步骤操作
-
在
Models
文件夹的IdentityModels.cs
文件中,将下面的类添加到Models
namespace
。public class ApplicationRole : IdentityRole { public ApplicationRole() : base() { } public ApplicationRole(string name) : base(name) { } }
-
在
App_Start
文件夹中IdentityConfig.cs
文件中,添加下面的类public class ApplicationRoleManager : RoleManager<ApplicationRole> { public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore) : base(roleStore) { } public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context) { return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>())); } }
-
转到
App_Start
文件夹中Startup.Auth.cs
文件,并将以下代码添加到ConfigureAuth
方法。app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
在此之后,您应该停止收到错误。
希望这有帮助。