加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – ASP.Net MVC 4和WebSecurity – 通过电子邮件

发布时间:2020-12-16 00:22:40 所属栏目:asp.Net 来源:网络整理
导读:我正在使用ASP.Net MVC 4项目的默认Internet应用程序模板。帐户控制器中的注册操作是这样的 – [HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public ActionResult Register(RegisterModel model){ if (ModelState.IsValid) { // Attempt to registe
我正在使用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);
}

但是,这并没有提供任何可以使用的功能来使用电子邮件地址进行注册,而且步骤可以发送电子邮件以进行确认。帐号激活。
我看到WebMatrix的Starter Site模板使用WebSecurity并提供了我正在寻找的功能,但它并不遵循标准的MVC模式。我可以混合这两种方法来达到MVC 4兼容的解决方案,但我正在寻找可以使用代码来节省时间。任何好的样品或指针都非常感谢。谢谢。

解决方法

实际上SimpleMembership有线支持2步确认。 Go to this blog post查看如何扩展UserProfile以包含电子邮件属性。修改注册视图以捕获电子邮件。现在,当您创建新用户使用 CreateUserAndAccount这样。
string confirmationToken = WebSecurity.CreateUserAndAccount(model.UserName,model.Password,new{Email = model.Email},true);

现在,您只需使用ASP.NET MVC最喜爱的电子邮件方式,向用户发送电子邮件确认信息。我喜欢Postal,因为您可以使用Razor引擎生成电子邮件的正文。电子邮件正文将包含一个指向作为id({controller} / {action} / {id}))的新网页(控制器/操作)的链接。当用户点击链接时,您的代码将使用WebSecurity.ConfirmAccount执行确认。这就是为您的MVC 4应用程序添加电子邮件确认所需要的。有一个step-by-step guide for adding email confirmation to MVC 4 here。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读