asp.net - Simplemembership - 添加电子邮件字段并用作登录名

标签 asp.net sql asp.net-mvc-4 visual-studio-2012 simplemembership

我想在这里做两件事:

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模型来自 UserNameEmail
  • 更新 InitializeSimpleMembershipAttribute使用电子邮件代替 UserName作为用户的自然键
  • 更新 AccountController LoginRegister操作,以便您在注册时捕获用户名和电子邮件,并在登录时使用电子邮件
  • 更新 View

  • 因此,要进行的实际更改是:
  • 模型/AccountModels.cs 更改
  • class UserProfile : 添加属性 public string Email { get; set; }
  • class LoginModel : 将属性名称从 UserName 更改为至 Email
  • class RegisterModel : 添加属性 public string Email { get; set; }并将其属性设置为 Required ,设置 Display(Name等等(如果您还想强制执行最大长度
  • AccountController变化
  • Login方法:
  • 更改 model.UserNamemodel.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);
  • 过滤器/InitializeSimpleMembershipAttribute.cs 更改
  • 更改 "UserName""Email"WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
  • View /帐户/Login.cshtml
  • 改变m.UserName的三种用法至 m.Email
  • View /帐户/Register.cshtml
  • 复制并粘贴用户名 <li>部分并更改重复项 m.UserNamem.Email

  • 在 vanilla Internet Application MVC 4 项目中,这些更改将完美地工作(在真正的 vanilla 项目中,如果您想使用这些并且不编辑数据库以添加 Email 列,则可能必须应用迁移)。

    关于asp.net - Simplemembership - 添加电子邮件字段并用作登录名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16529469/

    相关文章:

    c# - Resharper 建议但不对此代码块执行任何重构

    c# - 如何找到 Visual Studio Web 服务器应用程序池模式?

    sql - Oracle SQL : Using Variables in If Then Statement

    MySQL 按组中的值过滤

    ajax - PartialView 不起作用(整个页面刷新)

    azure - 如何使用 F# 将 Web 应用程序部署到 Azure 网站

    asp.net - 如何重置 ASP.NET 启动页?

    c# - 自定义验证器可能不显示错误消息的原因?

    mysql - 使用 MySQL 在后台运行 SQL 查询

    c# - MVC 条件验证?