获取captcha插件以使用注册操作

时间:2015-02-17 18:44:20

标签: asp.net-mvc-5 captcha

我的登录部分工作正常,注册页面显示验证码,RecaptchaMVC5的.dll表示AccountController不包含verifyReCAPTCHA的定义,但它适用于登录部分:

示例:

登录工作:

 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            // Verify the recaptcha response.
            ReCaptchaResponse response = await this.verifyReCAPTCHA(model, "key", true);
            if (response.Success)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }
            else
            {
                ModelState.AddModelError("", "Invalid Captcha Code!");
            }
        }

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

My Register Mockup会在verifyReCAPTCHA上抛出错误:

       [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            //Verify the recaptcha response.
            ReCaptchaResponse response = await this.verifyReCAPTCHA(model, "key", true);
            if (response.Success)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

我得到的错误

错误1&#39; ReCaptchaMVC5Test.Controllers.AccountController&#39;不包含&#39; verifyReCAPTCHA&#39;的定义

3 个答案:

答案 0 :(得分:2)

Inside Models文件夹&gt; AccountViewModels.cs有

public class LoginViewModel : ReCaptchaViewModel

public class RegisterViewModel : <Place 'RecaptchaViewModel' Here>

您如何将Captcha的视图模型分配给其他模型

答案 1 :(得分:1)

根据消息来源的说法,有一种您无法访问的扩展方法。您似乎需要将using ReCaptcha.Mvc5;添加到Controller的源文件顶部才能获得访问权限。

verifyReCAPTCHA(this Controller, ReCaptchaViewModel, String, Boolean)

此外,请确保您的model继承自ReCaptcha.Mvc5.Model.ReCaptchaViewModel(如documentation所示),这样您就可以满足方法签名。

答案 2 :(得分:1)

假设这两个方法都在AccountController上,那么verifyReCAPTCHA的方法签名是什么,因为方法发送不同的模型(LoginViewModel和RegisterViewModel)都是从正确的基础继承吗?