我想在这里做两件事:
1. 将电子邮件字段添加到(默认)UserProfile 表中。
奇迹般有效。
用户可以注册用户名和电子邮件。
2. 更改登录以使用电子邮件而不是用户名,这也很有效。
这是问题所在。以上仅在我将它们分开时才有效,只要我同时使用它们 注册过程失败 与以下 错误信息:
Cannot insert the value NULL into column 'UserName', table 'opdb.dbo.UserProfile'; column does not allow nulls. INSERT fails.
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email
});
WebSecurity.Login(model.Email, model.Password);
我或多或少地遵循
guide found here,
在评论部分,我看到其他人也有同样的问题,但是,解决方案不是将 UserName 字段设置为允许回复中所述的空值。
奇怪的是,只要我不同时使用两者,一切都有效。有任何想法吗?这让我发疯!
提前致谢
编辑 : 会不会是数据库中列的顺序?用于标识的字段需要是表中的第一列吗?那么,如果我想要电子邮件作为身份,需要成为表中的第一列?
最佳答案
这不是列顺序。我想你还没有设置你的 WebSecurity.InitializeDatabaseConnection
正确起来。听起来像当您添加电子邮件字段时,它被视为电子邮件字段(而不是用户的自然键),而当您更改登录名以使用电子邮件时,您实际上是将电子邮件插入到用户名列中?
无论哪种方式,工作都很简单。假设您已经在数据库中有您的电子邮件列并且您正在使用标准 Internet 应用程序模板,请执行以下操作:
UserProfile
模型添加 Email
属性,对 RegisterModel
做同样的事情并更改 Login
模型来自 UserName
至 Email
InitializeSimpleMembershipAttribute
使用电子邮件代替 UserName
作为用户的自然键AccountController
Login
和 Register
操作,以便您在注册时捕获用户名和电子邮件,并在登录时使用电子邮件 因此,要进行的实际更改是:
class UserProfile
: 添加属性 public string Email { get; set; }
class LoginModel
: 将属性名称从 UserName
更改为至 Email
class RegisterModel
: 添加属性 public string Email { get; set; }
并将其属性设置为 Required
,设置 Display(Name
等等(如果您还想强制执行最大长度 AccountController
变化Login
方法:model.UserName
至 model.Email
在线if (ModelState.IsValid && WebSecurity.Login(model.UserName ...
Register
方法:WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
至 WebSecurity.CreateUserAndAccount(model.Email, model.Password, new { UserName = model.UserName });
更改
WebSecurity.Login(model.UserName, model.Password);
至 WebSecurity.Login(model.Email, model.Password);
"UserName"
至 "Email"
在 WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
m.UserName
的三种用法至 m.Email
<li>
部分并更改重复项 m.UserName
至 m.Email
在 vanilla Internet Application MVC 4 项目中,这些更改将完美地工作(在真正的 vanilla 项目中,如果您想使用这些并且不编辑数据库以添加 Email 列,则可能必须应用迁移)。
关于asp.net - Simplemembership - 添加电子邮件字段并用作登录名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16529469/