San*_*osh 16 security asp.net-mvc-4 simplemembership
我正在使用ASP.Net MVC 4项目的默认Internet应用程序模板.帐户控制器中的注册操作是这样的 -
[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);
}
Run Code Online (Sandbox Code Playgroud)
但是,这并未提供任何可立即使用的功能来使用电子邮件地址进行注册,以及发送电子邮件以进行确认和帐户激活的步骤. 我看到WebMatrix的Starter Site模板使用WebSecurity并提供我正在寻找的功能,但它不遵循标准的MVC模式.我可以混合两种方法来获得MVC 4兼容解决方案,但我正在寻找准备好使用代码来节省时间.任何好的样品或指针都非常感谢.谢谢.
Kev*_*ans 32
实际上,SimpleMembership连线支持2步确认. 转到此博客文章,了解如何扩展UserProfile以包含Email属性.修改注册视图以捕获电子邮件.现在,当您创建新用户时,请使用CreateUserAndAccount.
string confirmationToken = WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new{Email = model.Email}, true);
Run Code Online (Sandbox Code Playgroud)
现在,您只需使用您最喜爱的ASP.NET MVC电子邮件方法将确认信息发送到用户的电子邮件中.我喜欢Postal,因为您可以使用Razor引擎生成电子邮件的正文.电子邮件正文将包含指向具有confirmToken作为id({controller}/{action}/{id})的新网页(控制器/操作)的链接.当用户单击链接时,您的代码将使用WebSecurity.ConfirmAccount执行确认.这就是将电子邮件确认添加到MVC 4应用程序所需的全部内容.这里有一个向MVC 4添加电子邮件确认的分步指南.