【问题标题】:How can I restrict access until user has confirmed email link在用户确认电子邮件链接之前如何限制访问
【发布时间】:2015-04-09 17:34:33
【问题描述】:

我终于可以在我的 MVC 5 应用程序上发送电子邮件确认

用户现在收到一封电子邮件,并且 EmailConfirmed 字段从 False 更新为 True。但是,用户仍然可以在不确认电子邮件的情况下登录。

我的问题是在用户确认电子邮件链接之前如何限制访问

下面是我的 ConfirmEmail 方法。

    // GET: /Account/ConfirmEmail
    [AllowAnonymous]
    public async Task<ActionResult> ConfirmEmail(string Token, string Email)
    {
        ApplicationUser user = this.UserManager.FindById(Token);
        if (user != null)
        {
            if (user.Email == Email)
            {
                user.EmailConfirmed = true;
                await UserManager.UpdateAsync(user);
                //await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home", new { ConfirmedEmail = user.Email });
            }
            else
            {
                return RedirectToAction("Confirm", "Account", new { Email = user.Email });
            }
        }
        else
        {
            return RedirectToAction("Confirm", "Account", new { Email = "" });
        }
    }

    [AllowAnonymous]
    public ActionResult Confirm(string Email)
    {
        ViewBag.Email = Email; return View();
    } 

感谢大家的阅读。

塞西

----- 更新 ------

我将下面的代码添加到 /Account/Login 控制器

    var user = await UserManager.FindByNameAsync(model.UserName);
    if(user != null){
        if (!await UserManager.IsEmailConfirmedAsync(user.UserName)) {
            return View("ErrorNotConfirmed");
        }
    }

但它返回一个错误。未找到用户 ID。

【问题讨论】:

  • 我看到您有一个字符串令牌,您需要将其转换为 int 以通过 Id 获取某些内容(如果您的数据库具有该 id 的 int 值),请尝试 Int32.Parse(token); 然后使用它作为 id 值

标签: asp.net-mvc asp.net-mvc-5


【解决方案1】:

我发布此代码以防有人需要。

基本上我用这段代码替换了上面的代码:

        var userid = UserManager.FindByEmail(model.UserName).Id;
        if (!UserManager.IsEmailConfirmed(userid))
        {
            return View("EmailNotConfirmed");
        }

现在效果很好。

【讨论】:

    猜你喜欢
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多