我使用ASP.NET Identity,当用户想要注册时会收到此错误:
值不能为空。\ r \ nParameter name:manager。
这是我的注册行动代码:
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);
答案 0 :(得分:0)
由于未初始化角色管理器而出现错误
要解决此问题,请按照以下步骤操作
在IdentityModels.cs
文件夹的Models
文件中,将下面的类添加到Models
namespace
。
public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base() { }
public ApplicationRole(string name) : base(name) { }
}
在IdentityConfig.cs
文件夹中的App_Start
文件中,添加下面的类
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>()));
}
}
转到Startup.Auth.cs
文件夹中的App_Start
文件,并将下面的代码添加到ConfigureAuth
方法中。
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
此后您应该停止获取错误。
希望这会有所帮助。