ASP.NET令牌错误重置密码

ASP.NET token error reset password

我只是在我的项目中添加了 MVC 5 的 "forgot password" 部分,收到电子邮件后我无法更改密码。

error:In应用=>Image of error in the app

在Visual Studio=>Image of error visual studio

错误来源代码:

 public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var user = await UserManager.FindByEmailAsync(model.Email);
        if (user == null)
        {
            // Don't reveal that the user does not exist
            return RedirectToAction("ResetPasswordConfirmation", "Account");
        }
        var code = model.Code.Replace(" ","+");
        **var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);**
        if (result.Succeeded)
        {
            return RedirectToAction("ResetPasswordConfirmation", "Account");
        }
        AddErrors(result);
        return View();
    }

我尝试了很多在 Whosebug 和其他网站上找到的东西,但都没有用。

如果你知道为什么我会收到这个错误:)

我使用在 visual studio 中创建 ASP.NET 网络应用程序时提出的基本模板。 我可以上传你想要的所有代码文件,只要问你需要什么帮助我,我会在 2 分钟内上传!

谢谢

假设您使用的是默认模板,您可能会使用以下代码生成 callbackUrl

string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

您需要对 code(标记)进行 url 编码,然后再将其发送到电子邮件,即将其更改为 code = HttpUtility.UrlEncode(code)

你不需要这一行var code = model.Code.Replace(" ","+");

希望对您有所帮助。

我知道问题出在哪里了,

我的 callbackUrl 的格式包含令牌特殊字符和大写

首先在 ForgotPasswordViewModel 中,我手动生成了我的 URL,然后我对其进行了正确的编码

            string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
            code = System.Web.HttpUtility.UrlEncode(code);
            string datcode = code;
            //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            var datUrl = "http://localhost:62989/Account/Resetpassword?" + user.Id + "&Code=" + code;

对于大写问题,我在为我的 emai 消息分配 callbackurl 时忘记了 ToTitleCase 方法,所以我删除了它。

            message = message.Replace("@ViewBag.Name", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(usernom));
            message = message.Replace("@ViewBag.CallBackUrl", datUrl);
            await MessageServices.SendEmailAsync(model.Email, emailSubject, message);

其次,在 ResetPasswordViewModel 中,我使用

对令牌进行解码
var code = WebUtility.UrlDecode(model.Code);

并将空格space替换为原来的+,

code = code.Replace(' ', '+');

它终于在 ResetPasswordAsync 函数中运行良好!

var result = await UserManager.ResetPasswordAsync(user.Id, code, model.Password);

感谢@Ravi 的帮助

我的问题非常相似,但碰巧是我的路由引擎将所有 URL 转换为小写(用于 SEO 等)。我需要确保查询字符串参数允许混合大小写。 Base64 使用大小写混合。

我将 NoLowercaseQueryString 属性添加到我的每个控制器方法中。这是特定于 MVC Boilerplate project.