I am using the default Internet Application template of ASP.Net MVC 4 project. The Register action in the Account controller is like this -
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, 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);
}
However, this does not provide any ready to use functionality to use email address for registration and steps to send email for confirmation & account activation. I see that Starter Site template of WebMatrix uses WebSecurity and provides the functionality I'm looking for, but it does not follow the standard MVC pattern. I could blend both the approaches to arrive at MVC 4 compatible solution, but I am looking for ready to use code to save time. Any good samples or pointers are very much appreciated. Thank you.
Actually SimpleMembership is wired to support a 2 step confirmation. Go to this blog post to see how you extend the UserProfile to include an Email property. Modify the registration view to capture the email. Now when you create the new user use CreateUserAndAccount like this.
string confirmationToken = WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new{Email = model.Email}, true);
Now you just send the confirmationToken in an email to the user using your favorite emailing method for ASP.NET MVC. I like Postal because you can use the Razor engine to generate the body of your email. The email body will contain a link to a new web page (controller/action) that has the confirmationToken as the id ({controller}/{action}/{id}). When the user clicks on the link your code will perform the confirmation using WebSecurity.ConfirmAccount. That is all that is required to add email confirmation to your MVC 4 application. There is a step-by-step guide for adding email confirmation to MVC 4 here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With