我已经尝试了所有可以在 SO 上找到的答案。我正在尝试将身份添加到我的 ASP.NET MVC 5 项目中。我首先使用数据库。已经有一个现有的数据库。我使用此 GitHub 中的脚本在我的数据库中创建身份表。
https://gist.github.com/jeroenheijmans/8fa79427abc25a864cb055616644172f
这是我的 Startup.cs 文件
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(() => new AppDbContext());
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<RoleManager<AspNetRole>>((options, context) =>
new RoleManager<AspNetRole>(
new RoleStore<AspNetRole>(context.Get<AppDbContext>())));
app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
}
这是我的应用程序用户管理器:
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(() => new AppDbContext());
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<RoleManager<AspNetRole>>((options, context) =>
new RoleManager<AspNetRole>(
new RoleStore<AspNetRole>(context.Get<AppDbContext>())));
app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
}
这是我的注册操作:
public async Task<ActionResult> Register()
{
var model = (RegisterUserModel)Session["RegisterAccount"];
var user = new AspNetUser()
{
UserName = model.Email,
Email = model.Email
};
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
IdentityResult addUserResult = await userManager.CreateAsync(user, model.Password);
}
我的角色类
public partial class AspNetRole : IdentityRole
{
public AspNetRole(string name) { Name = name; }
}
我的用户类
public partial class AspNetUser : IdentityUser
{
}
我的数据库上下文
public partial class AppDbContext: IdentityDbContext<AspNetUser>
{
public AppDbContext(string connectionString)
: base(connectionString)
{}
}
最佳答案
检查 model.Email
值。它似乎是空的。为了确定,将 Register
方法放入 try-catch
block 中,并尝试提取有关错误/异常的更多详细信息:
public async Task<ActionResult> Register()
{
try
{
var model = (RegisterUserModel)Session["RegisterAccount"];
var user = new AspNetUser()
{
UserName = model.Email,
Email = model.Email
};
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
IdentityResult addUserResult = await userManager.CreateAsync(user, model.Password);
if (!addUserResult.Succeeded)
{
//loop over addUserResult.Errors for more detail
}
}
catch (Exception exception)
{
//here, check the exception for more details
}
}
关于c# - ASP.NET Identity CreateAsync 返回错误 "Name cannot be null or empty.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57824487/