locked
MVC ReCaptcha RRS feed

  • Question

  • User1859059268 posted
    Hey all. I am trying to get ReCaptcha to work on my MVC application and I just can't seem to wrap my head around getting the validated recaptcha to interact with my backend controller.
    The reason I wan't to add a captcha to my site is because it is a mailer controller and I don't want anyone to use my mailer to spam the world.
    I have created a controller called FunclibController.
    The funclib controller accepts an id(used to fetch the data to be mailed) and following some of the reCpatcha tutorials accepts a bool value for captcha valid. Code below:
    [CaptchaValidator]
            [AcceptVerbs (HttpVerbs.Post)]    
            public ActionResult mailer(int id, bool captchaValid)
            {
        
    
                t_company t_company = db.t_company.Find(id);
    
                try
                {
                    SmtpClient myClient = new SmtpClient("", 25);
    
                    MailMessage myMessage = new MailMessage("noreply@bizboard.co.za", foo@foo.com);
    
                    myMessage.Subject = t_company.CompanyName + " Details courtesy of Bizboard.";
                    myMessage.Body = "Test Mail";
    
                    myClient.Send(myMessage);
                    ViewBag.message = "Mail sent Successfully";
                    return View();
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    ViewBag.message = "Error Occured, please review below:";
    
                    return View();
                }            
            }               
    So this should in all theory only execute if the captcha is valid.
    I have rendered the captcha control on a view, and i want this captcha to validate the actionlink I am using to send the email.
    So the View looks like this:
    Other detail above ***
    
    <div>@Html.ActionLink("Email this info to me", "mailer", "Funclib", new { id = @Model.ID }, null)</div>
    
    @Html.Raw(Html.GenerateCaptcha())
     
    So with those two lines i have an actionlink that calls the mailer controller  and a recaptcha on my page. How do I get the actionlink to read the validity of the captcha?
    I just can't wrap my head around how to do it :(
     
    Friday, May 6, 2011 4:45 PM

Answers

  • User1859059268 posted

    Ok so by mashing all the tutorials together this is what is required, with the latest MVC dll's etc:

    Download the DLL, and generate your keys for recaptcha.

    add keys to you web.config as part of appSettings

     

    <add key="ReCaptchaPrivateKey" value="key" />
        <add key="ReCaptchaPublicKey" value="key" />

    create the action filter: 

     

    public class CaptchaValidatorAttribute : ActionFilterAttribute
            { 
                private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
                private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";
    
                public override void OnActionExecuting(ActionExecutingContext filterContext)
                {
                    var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY];
                    var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY];
    
                    var captchaValidator = new Recaptcha.RecaptchaValidator
                    {
                        PrivateKey = "key",
                        RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
                        Challenge = captchaChallengeValue,
                        Response = captchaResponseValue
                    };
    
                    var recaptchaResponse = captchaValidator.Validate();
    
                    filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid;
                    
                    base.OnActionExecuting(filterContext);
                }

    Then add the following the the controller accepting the captcha verification: 

     

    [CaptchaValidator]
            [AcceptVerbs (HttpVerbs.Post)]
            public ActionResult mailer(int id, bool captchaValid)

     

    if (!captchaValid)
                {
                    ModelState.AddModelError("", "You did not type the verification word correctly. Please try again.");
                    return View();
                }
                else
                {}

    The else logic is what you want the controller to do. 

    Then on your view you need the following:

    <form method="post" action="@Url.Action("action", "controller", new { param = @Model.param })">
        <input type="submit" value="Name of Button" />
        @Html.Raw(Html.GenerateCaptcha())
    </form>

    That will work. The captcha validator passes the value to the controller, you just need to pass your own parameters.

     Thanks for all the contributions to this thread guys.

     

     

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 9, 2011 7:58 AM

All replies

  • User401360897 posted

    http://weblogs.asp.net/imranbaloch/archive/2010/11/07/using-asp-net-web-pages-in-asp-net-mvc.aspx

    http://www.dotnetcurry.com/ShowArticle.aspx?ID=611

    Saturday, May 7, 2011 1:02 AM
  • User1859059268 posted

    Thanks for the reply. Those two articles don't cover using the actionfilter to stop the controller from being invoked directly. I will continue searching.

    Saturday, May 7, 2011 3:45 PM
  • User1064071399 posted

    Be a pal, save me some time and post your solution if you get one here?

    Some links will be nice too.  Never used Captcha in MVC and got to do it in the next day or two.

    Saturday, May 7, 2011 4:09 PM
  • User401360897 posted

    You needt to use form element. Just follow the above tutorial.

    Sunday, May 8, 2011 1:57 AM
  • User1859059268 posted

    I followed the tutorial and I am getting namespace errors, I think it has changed since mvc 3's latest updates.

    Sunday, May 8, 2011 4:34 PM
  • User401360897 posted

    I followed the tutorial and I am getting namespace errors, I think it has changed since mvc 3's latest updates.

    Is you adding this through NuGet?

    What error yuo are getting?

    Sunday, May 8, 2011 11:04 PM
  • User1859059268 posted

    Ok so by mashing all the tutorials together this is what is required, with the latest MVC dll's etc:

    Download the DLL, and generate your keys for recaptcha.

    add keys to you web.config as part of appSettings

     

    <add key="ReCaptchaPrivateKey" value="key" />
        <add key="ReCaptchaPublicKey" value="key" />

    create the action filter: 

     

    public class CaptchaValidatorAttribute : ActionFilterAttribute
            { 
                private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
                private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";
    
                public override void OnActionExecuting(ActionExecutingContext filterContext)
                {
                    var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY];
                    var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY];
    
                    var captchaValidator = new Recaptcha.RecaptchaValidator
                    {
                        PrivateKey = "key",
                        RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
                        Challenge = captchaChallengeValue,
                        Response = captchaResponseValue
                    };
    
                    var recaptchaResponse = captchaValidator.Validate();
    
                    filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid;
                    
                    base.OnActionExecuting(filterContext);
                }

    Then add the following the the controller accepting the captcha verification: 

     

    [CaptchaValidator]
            [AcceptVerbs (HttpVerbs.Post)]
            public ActionResult mailer(int id, bool captchaValid)

     

    if (!captchaValid)
                {
                    ModelState.AddModelError("", "You did not type the verification word correctly. Please try again.");
                    return View();
                }
                else
                {}

    The else logic is what you want the controller to do. 

    Then on your view you need the following:

    <form method="post" action="@Url.Action("action", "controller", new { param = @Model.param })">
        <input type="submit" value="Name of Button" />
        @Html.Raw(Html.GenerateCaptcha())
    </form>

    That will work. The captcha validator passes the value to the controller, you just need to pass your own parameters.

     Thanks for all the contributions to this thread guys.

     

     

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 9, 2011 7:58 AM