Getting bad request in Rick Anderson's code fo

2019-08-09 12:03发布

问题:

I am trying to create a password recover feature in Rick Anderson's post here (http://www.asp.net/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity). This basically allows a user who has lost pass to get an email with a link containing a token. When they are verified on arrival back to site they get a rest page. Everything worked fine in Rick's example, except when I got to the line of code where the callbackURL is generated I got a Bad Request error. As far as I could tell it is caused by all those extra characters in the token and browsers won't accept? Could someone point me to a solution? Thanks, Sanjeev

// POST: /Account/ForgotPassword
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
                ViewBag.Link = callbackUrl;
                return View("ForgotPasswordConfirmation");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

回答1:

Use HttpUtility.UrlEncode on callbackUrl before you add it to the string.