Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 583161
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T14:45:49+00:00 2026-05-13T14:45:49+00:00

I’m implementing CAPTCHA in my form submission as per Sanderson’s book Pro ASP.NET MVC

  • 0

I’m implementing CAPTCHA in my form submission as per Sanderson’s book Pro ASP.NET MVC Framework.

The view fields are generated with:

<%= Html.Captcha("testCaptcha")%>
<%= Html.TextBox("attemptCaptcha")%>

The VerifyAndExpireSolution helper is not working as his solution is implemented.

I’m adding validation and when it fails I add a ModelState error message and send the user back to the view as stated in the book:

return ModelState.IsValid ? View("Completed", appt) : View();

But, doing so, generates a new GUID which generates new CAPTCHA text.

The problem is, however, that the CAPTCHA hidden field value and the CAPTCHA image url both retain the original GUID. So, you’ll never be able to enter the correct value. You basically only have one shot to get it right.

I’m new to all of this, but it has something to do with the view retaining the values from the first page load.

Captcha is generated with:

public static string Captcha(this HtmlHelper html, string name)
{
    // Pick a GUID to represent this challenge
    string challengeGuid = Guid.NewGuid().ToString();
    // Generate and store a random solution text
    var session = html.ViewContext.HttpContext.Session;
    session[SessionKeyPrefix + challengeGuid] = MakeRandomSolution();

    // Render an <IMG> tag for the distorted text,
    // plus a hidden field to contain the challenge GUID
    var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
    string url = urlHelper.Action("Render", "CaptchaImage", new{challengeGuid});
    return string.Format(ImgFormat, url) + html.Hidden(name, challengeGuid);
}

And then I try to validate it with:

public static bool VerifyAndExpireSolution(HttpContextBase context,
                                       string challengeGuid,
                                       string attemptedSolution)
{
    // Immediately remove the solution from Session to prevent replay attacks
    string solution = (string)context.Session[SessionKeyPrefix + challengeGuid];
    context.Session.Remove(SessionKeyPrefix + challengeGuid);

    return ((solution != null) && (attemptedSolution == solution));
}

What about re-building the target field names with the guid? Then, each field is unique and won’t retain the previous form generations’ value?

Or do I just need a different CAPTCHA implementation?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T14:45:49+00:00Added an answer on May 13, 2026 at 2:45 pm

    So, I decided to implement reCaptcha. And I’ve customized my view likewise:

    <div id="recaptcha_image"></div>&nbsp;
         <a href="#" onclick="Recaptcha.reload();">
                generate a new image
         </a><br />
    <input type="text" name="recaptcha_response_field" 
               id="recaptcha_response_field" />
               &nbsp;<%= Html.ValidationMessage("attemptCaptcha")%>
    <script type="text/javascript" 
         src="http://api.recaptcha.net/challenge?k=[my public key]"></script>
    

    This creates two captchas- one in my image container, and another created by the script. So, I added css to hide the auto-generated one:

    <style type="text/css">
        #recaptcha_widget_div {display:none;}
    </style>
    

    Then, in my controller, I merely have to test for captchaValid:

    [CaptchaValidator]
    [AcceptVerbs(HttpVerbs.Post)]
    public ViewResult SubmitEssay(Essay essay, bool acceptsTerms, bool captchaValid)
    {
        if (!acceptsTerms)
            ModelState.AddModelError("acceptsTerms", 
                         "You must accept the terms and conditions.");
        else
        {
           try
           {
                // save/validate the essay
                var errors = essay.GetRuleViolations(captchaValid);
                if (errors.Count > 0)
                    throw new RuleException(errors);
    
            }
            catch (RuleException ex)
            {
                ex.CopyToModelState(ModelState, "essay");
            }
        }
        return ModelState.IsValid ? View("Completed", essay) : View();
    }
    
    public NameValueCollection GetRuleViolations(bool captchaValid)
    {
        var errors = new NameValueCollection();
        if (!captchaValid)
            errors.Add("attemptCaptcha", 
                 "Please enter the correct verification text before submitting.");
        // continue with other fields....
    }
    

    And all of this assumes that you’ve implemented the Action Filter attribute and the view helper as detailed at recaptcha.net:

    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 captchaValidtor = new Recaptcha.RecaptchaValidator
              {
                  PrivateKey = "[my private key]",
                  RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
                  Challenge = captchaChallengeValue,
                  Response = captchaResponseValue
              };
    
            var recaptchaResponse = captchaValidtor.Validate();
    
        // this will push the result value into a parameter in our Action
            filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid;
    
            base.OnActionExecuting(filterContext);
        }
    }
    

    html helper:

    public static class Captcha
    {
        public static string GenerateCaptcha( this HtmlHelper helper )
        {  
        var captchaControl = new Recaptcha.RecaptchaControl
            {
                ID = "recaptcha",
                Theme = "clean",
                PublicKey = "[my public key]",
                PrivateKey = "[ my private key ]"
            };
        var htmlWriter = new HtmlTextWriter( new StringWriter() );
            captchaControl.RenderControl(htmlWriter);
        return htmlWriter.InnerWriter.ToString();
        }
    }
    

    Hope this helps someone who got stuck with the implementation in the book.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a text area in my form which accepts all possible characters from
I have a view passing on information from a database: def serve_article(request, id): served_article
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.