简体   繁体   English

如何在ASP.NET MVC 4简单成员资格中使用“电子邮件”而不是“用户名”登录

[英]How to sign in with “E-Mail” instead of “UserName” in ASP.NET MVC 4 Simple Membership

I am developing an entry level application with ASP.NET MVC 4. The application will have a membership system. 我正在使用ASP.NET MVC 4开发入门级应用程序。该应用程序将具有成员资格系统。 I want to use integrated SimpleMembershipProvider because creating a new one will be complex for me. 我想使用集成的SimpleMembershipProvider,因为创建一个新的对我来说很复杂。 So the users must log in to application with their e-mail adresses instead of user name as in SimpleMembershipProvider. 因此,用户必须使用电子邮件地址而不是SimpleMembershipProvider中的用户名登录应用程序。 But I couldn't make this change. 但是我不能做这个改变。 Is the only way to do this is creating my own membership provider? 唯一的方法就是创建自己的会员资格提供程序吗?

Use the email to find the id of the user. 使用电子邮件查找用户的ID。 pass that user to membership and authenticate the user with that. 将该用户传递给成员身份,并以此验证用户身份。

you may also want to prevent duplicate emails at the time of registering user to make sure 1 email returns 1 account. 您可能还希望在注册用户时防止重复的电子邮件,以确保1封电子邮件返回1个帐户。 the following post will help in this senario: 以下帖子将有助于解决这个问题:

How does one prevent duplicate email addresses while users modify their email addresses after registration using the default MVC Membership Provider? 当用户使用默认的MVC成员资格提供程序注册后修改其电子邮件地址时,如何防止重复的电子邮件地址?

Also you may create a unique key in the table for the emails to ensure no duplicate emails will be registered. 另外,您可以在表格中为电子邮件创建唯一的密钥,以确保不会注册重复的电子邮件。

In the AccountModels class ( Models.AccountModels ) You have to update field ie introduce an email property as the following 在AccountModels类(Models.AccountModels)中,您必须更新字段,即引入如下的电子邮件属性

 public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    // Make change here 
    [Required]
    [Display(Name = "Your Email")]
    public string  Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

After we got the email then to use email in the login view , first of all change the LoginModel class as the following 获得电子邮件后,可以在登录视图中使用电子邮件,首先将LoginModel类更改为以下内容

    public class LoginModel
{
    [Required]
    [Display(Name = "Your Email")]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

And of course , Email will take from user when they register , so making change on the RegisterModel class as the following 当然,当用户注册时,电子邮件将从用户那里获取,因此对RegisterModel类进行如下更改

Now you have got login and register are updated. 现在您已经登录并注册了。 Then The actual data which is will eventually store in the database is define in the UserProfile class so , let's add and Email field to it. 然后,将最终存储在数据库中的实际数据在UserProfile类中定义,因此,我们向其中添加和Email字段。

    [Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email  { get; set; }
}

Now you are done with update the model. 现在您完成了更新模型。 But this will now work yet, because when you click register it will actually add userName and Password and use the pair for authentication. 但这现在仍然有效,因为当您单击注册时,它实际上会添加userName和Password并使用该对进行身份验证。 Now let's change it . 现在让我们进行更改。 Navigate to Controllers.AccountController.cs and find the following function and update it. 导航到Controllers.AccountController.cs并找到以下函数并进行更新。 WebSecurity.CreateUserAndAccount(model.Email, model.Password); WebSecurity.CreateUserAndAccount(model.Email,model.Password); WebSecurity.Login(model.Email, model.Password); WebSecurity.Login(model.Email,model.Password);

//
    // POST: /Account/Register

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.Email, model.Password);
                WebSecurity.Login(model.Email, model.Password);
                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

And Finally of course , change the Login action as the following. 最后,当然,更改登录操作如下。

        //
    // POST: /Account/Login

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
        {
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The Email or password provided is incorrect.");
        return View(model);
    }

This should allow you to use email and password as a login pair. 这应该允许您将电子邮件和密码用作登录对。

An easy option: in file Models/AccountViewModels.cs, you find many classes containing a field like this: 一个简单的选择:在Models / AccountViewModels.cs文件中,您会找到许多包含如下字段的类:

[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }

Just for speed change them to: 为了提高速度,请将其更改为:

[Required]
[Display(Name = "Username")]
public string Email { get; set; }

And from your code you know that Email field is actually the username, thus you don't have to change everywhere. 从您的代码中,您知道Email字段实际上是用户名,因此您不必在任何地方进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM