Asp.net mvc MVC5应用程序:创建模型状态无效的标识用户结果?
我正在将一个正在开发中的应用程序从MVC4/EF5升级到MVC5/EF6,以利用(除其他外)ASP.Net标识。当我尝试创建用户时,我的代码将模型标记为无效,而不是创建用户。我的视图只是显示一个输入电子邮件的框,然后是一个开关,允许登录管理员通过一些下拉列表选择MemberOrganization或赞助商来分配新用户2 my UserController的Create()方法如下:Asp.net mvc MVC5应用程序:创建模型状态无效的标识用户结果?,asp.net-mvc,asp.net-mvc-5,entity-framework-6,asp.net-identity,modelstate,Asp.net Mvc,Asp.net Mvc 5,Entity Framework 6,Asp.net Identity,Modelstate,我正在将一个正在开发中的应用程序从MVC4/EF5升级到MVC5/EF6,以利用(除其他外)ASP.Net标识。当我尝试创建用户时,我的代码将模型标记为无效,而不是创建用户。我的视图只是显示一个输入电子邮件的框,然后是一个开关,允许登录管理员通过一些下拉列表选择MemberOrganization或赞助商来分配新用户2 my UserController的Create()方法如下: // GET: Admin/UserManagement/Create publi
// GET: Admin/UserManagement/Create
public ActionResult Create()
{
ViewBag.headerTitle = "Create User";
ViewData["Organization"] = new SelectList(db.MemberOrganizations, "Id", "Name");
ViewData["Sponsor"] = new SelectList(db.SponsorOrganizations, "Id", "Name");
ViewBag.SwitchState = true;
ApplicationUser newUser = new ApplicationUser();
newUser.RegisteredDate = DateTime.Now;
newUser.LastVisitDate = DateTime.Now;
newUser.ProfilePictureSrc = null;
return View(newUser);
}
// POST: Admin/UserManagement/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Property1, Property2, etc.")] ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
ViewBag.headerTitle = "Create User";
PasswordHasher ph = new PasswordHasher();
var password = ph.HashPassword("aR@nD0MP@s$w0r9");
var user = new ApplicationUser() { UserName = applicationUser.UserName, Email = applicationUser.Email, PasswordHash = password };
IdentityResult result = await UserManager.CreateAsync(user, user.PasswordHash);
if (result.Succeeded)
{
await db.SaveChangesAsync();
return RedirectToAction("Index", "UserManagement");
}
else
{
ModelState.AddModelError("", "Failed to Create User.");
}
}
ModelState.AddModelError("", "Failed to Create User.");
var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
var errors2 = ModelState.Values.SelectMany(v => v.Errors);
ViewData["Organization"] = new SelectList(db.MemberOrganizations, "Id", "Name", applicationUser.MemberOrgId);
ViewData["Sponsor"] = new SelectList(db.SponsorOrganizations, "Id", "Name", applicationUser.SponsorOrgId);
if (applicationUser.MemberOrgId != null)
{
ViewBag.SwitchState = true;
}
else
{
ViewBag.SwitchState = false;
}
ViewBag.OrganizationId = new SelectList(db.MemberOrganizations, "Id", "State", applicationUser.MemberOrgId);
// If we got this far, something failed, redisplay form
return View(applicationUser);
}
当我检查结果的值
并深入到错误->[string[]]->[0]
时,错误消息是:名称不能为null或空
。有人对此有想法吗?我在视图中添加了一个字段来指定新用户名称
,并将其合并到上面的新应用程序user()
代码行中。我不确定我在哪里遗漏了什么
EDIT2:
Create()视图[相关]:
@model PROJECTS.Models.ApplicationUser
@{
ViewBag.Title = "Create";
Layout = "~/Areas/Admin/Views/Shared/_LayoutAdmin.cshtml";
string cancelEditUrl = "/Admin/UserManagement/";
}
@using (Html.BeginForm("Create", "UserManagement", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.RegisteredDate)
<div class="container">
<div class="row">
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field" style="margin-bottom: 15px">
@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="row">
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field" style="margin-bottom: 15px">
@Html.TextBoxFor(model => model.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Email)
</div>
</div>
....
@model PROJECTS.Models.ApplicationUser
@{
ViewBag.Title=“创建”;
Layout=“~/Areas/Admin/Views/Shared/_LayoutAdmin.cshtml”;
字符串cancelEditUrl=“/Admin/UserManagement/”;
}
@使用(Html.BeginForm(“Create”、“UserManagement”、FormMethod.Post、new{enctype=“multipart/formdata”}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(model=>model.RegisteredDate)
@LabelFor(model=>model.Name)
@Html.TextBoxFor(model=>model.Name,新的{@class=“form control”})
@Html.ValidationMessageFor(model=>model.Name)
@LabelFor(model=>model.Email)
@Html.TextBoxFor(model=>model.Email,新的{@class=“form control”})
@Html.ValidationMessageFor(model=>model.Email)
....
正如您在上一张图片中所看到的,您在值字符串为.Empty(“”)的属性赞助商组织ID上有一个错误。可能应用程序用户中的赞助商组织ID具有[Required]属性
编辑
关于您在尝试将用户添加到数据库时遇到的问题(这是在您调用UserManager.Create(user,password)时发生的)
然后,您可以调试“errors”的值或从您的ModelState读取错误消息
关于你的编辑
将名称添加到此部件:
var user = new ApplicationUser() { UserName = applicationUser.UserName, Email = applicationUser.Email, PasswordHash = password, Name = applicationUser.Name };
编辑2
问题是无法创建没有用户名的用户。但是您可以将用户的电子邮件添加到用户名中,然后将其更改为用户指定的用户名。要使其通过验证,您需要添加此部分
UserManager.UserValidator = new UserValidator<User>(UserManager) { RequireUniqueEmail = true };
UserManager.UserValidator=newuservalidator(UserManager){RequireUniqueEmail=true};
我意识到回复已经晚了,但在解决这个问题之前,我读了四篇关于这个问题的文章。这并不完全明显,而且似乎是与自定义属性的继承冲突。我的问题的根源是我创建了一个UserName属性-一个我想定义为FirstName+的自定义属性(…或者我认为是这样)+姓氏
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
// public new string UserName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
...remainder removed for clarity.
如果您的applicationuser类中有用户名和电子邮件属性,则这些属性将隐藏实际属性,因此请将它们从应用程序类中删除。这将解决问题。感谢您的回复Rikard。您是正确的,我已解决了这个特定问题,因为只能选择赞助商或MemberOrg,而不能同时选择两者。现在如何ver my code处理到第
if(result.succeed)
行,然后跳转到带有ModelState.AddModelError(“,”未能创建用户“)的myelse
子句
。有没有关于如何调试这个新行为的想法?谢谢Rikard的持续帮助。我修改了你的建议:var user=new ApplicationUser(){UserName=ApplicationUser.UserName,Email=ApplicationUser.Email,PasswordHash=password,Name=ApplicationUser.Name};
但还是没有运气。“名称不能为null或空
"。然后,问题是您没有从用户输入中捕获名称。输入应用程序用户的名称随后为null或空。因此,您需要在前端向我提供代码。我认为您可能是正确的。我已将相关部分添加到EDIT2下的查看代码中。您是否在应用程序用户中收到电子邮件?您是否已将名称复制到新的应用程序中“ApplicationUser”我根据您的建议进行了修改:var user=new ApplicationUser(){UserName=ApplicationUser.UserName,Email=ApplicationUser.Email,PasswordHash=password,Name=ApplicationUser.Name};
但仍然不走运。“名称不能为空。”。
UserManager.UserValidator = new UserValidator<User>(UserManager) { RequireUniqueEmail = true };
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
// public new string UserName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
...remainder removed for clarity.
namespace Microsoft.AspNet.Identity
{
// Summary:
// Minimal interface for a user with id and username
//
// Type parameters:
// TKey:
public interface IUser<out TKey>
{
// Summary:
// Unique key for the user
TKey Id { get; }
//
// Summary:
// Unique username
string UserName { get; set; }
}
}
[...] warning CS0114: 'MyApp.Models.ApplicationUser.UserName' hides inherited member 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser<string,Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin,Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole,Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim>.UserName'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
var user = new ApplicationUser() { UserName = applicationUser.UserName, Email = applicationUser.Email, PasswordHash = password };