Una volta modificato il form html per la registrazione del nuovo utente dobbiamo effettuare un’ultima modifica nella parte di codice che si occupa di recuperare i dati che sono inviati dal form di registrazione e di salvarli sul nostro database.

Queste operazioni sono normalmente svolte dal Controller.

Modifica Controller Registrazione

Ora procederemo alla modifica del metodo Register che riceve i dati dopo che l’utente ha cliccato sul bottone Register del form di registrazione.

Nella cartella Controllers apriamo il file AccountController e cerchiamo il metodo Register con l’attributo [HttpPost]:

// POST: /Account/Register
         [HttpPost]
         [AllowAnonymous]
         [ValidateAntiForgeryToken]
         public async Task<ActionResult> Register(RegisterViewModel model)
         {
             if (ModelState.IsValid)
             {
                 var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                 var result = await UserManager.CreateAsync(user, model.Password);
                 if (result.Succeeded)
                 {
                     await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
            
                     return RedirectToAction("Index", "Home");
                 }
                 AddErrors(result);
             }

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

Ora modifichiamo il metodo Register del nostro controller in base alle nostre esigenze:

// POST: /Account/Login
      [HttpPost]
      [AllowAnonymous]
      [ValidateAntiForgeryToken]
      public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
      {
          if (!ModelState.IsValid)
          {
              return View(model);
          }

          // This doesn't count login failures towards account lockout
          // To enable password failures to trigger account lockout, change to shouldLockout: true
          var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
          switch (result)
          {
              case SignInStatus.Success:
                  return RedirectToLocal(returnUrl);
              case SignInStatus.LockedOut:
                  return View("Lockout");
              case SignInStatus.RequiresVerification:
                  return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
              case SignInStatus.Failure:
              default:
                  ModelState.AddModelError("", "Invalid login attempt.");
                  return View(model);
          }
      }

Ora possiamo procedere con un test:

Compiliamo e mandiamo in esecuzione la nostra applicazione tramite la combinazione di tasti Ctrl + F5

Una volta partito il nostro web site premiamo sulla voce Register in alto a sinistra

image

A questo punto potremo effettuare una registrazione di test nel nostro form personalizzato:

Img_152711193317

Come ultima cosa ci rimane da modificare il codice che si occupa del login dell’utente in quanto per default ASP.NET Identity utilizza L’email come username.

Procediamo con le seguenti modifiche:

Modello LoginViewModel

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

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

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

View Login.cshtml

@using MvcCustomIdentity.Models
@model LoginViewModel
@{
    ViewBag.Title = "Log in";
}

<h2>@ViewBag.Title.</h2>
<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()
                <h4>Use a local account to log in.</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(m => m.Username, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Username, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <div class="checkbox">
                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Log in" class="btn btn-default" />
                    </div>
                </div>
                <p>
                    @Html.ActionLink("Register as a new user", "Register")
                </p>
                @* Enable this once you have account confirmation enabled for password reset functionality
                    <p>
                        @Html.ActionLink("Forgot your password?", "ForgotPassword")
                    </p>*@
            }
        </section>
    </div>
    <div class="col-md-4">
        <section id="socialLoginForm">
            @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })
        </section>
    </div>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Controller Login

// POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }

Ora abbiamo terminato tutte le modifiche necessarie alla nostra implementazione.

Occhiolino

Autore:


blog comments powered by Disqus