Asp.Net Mvc Sample code

597 views
Skip to first unread message

Benoit R.

unread,
Dec 3, 2014, 4:49:31 PM12/3/14
to reca...@googlegroups.com
Hi,
I have not found sample on for Asp.Net Mcv, i give you mine. 
With only the  "HelperReCaptcha.cs" File in your project, you will be able to use this awsome Captcha in 2 line of code :)
 

HelperReCaptcha.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
 
namespace System.Web.Mvc.Html
{
   
public static class ReCaptcha
   
{
       
//https://developers.google.com/recaptcha/docs/verify
 
       
public static MvcHtmlString ReCaptcha(this HtmlHelper helper, ReCaptchaModel.Theme theme = ReCaptchaModel.Theme.light)
       
{
           
var themeStr = theme != ReCaptchaModel.Theme.light ? " data-theme='" + theme.ToString() + "' " : "";
           
var sb = new StringBuilder();
            sb
.Append(helper.ValidationMessage("Captcha").ToString());
            sb
.Append("<script src='https://www.google.com/recaptcha/api.js' async defer></script>");
            sb
.Append("<div class='g-recaptcha'" + themeStr + " data-sitekey='" + Config.reCAPTCHA.SiteKey + "'></div>");
            sb
.Append("<noscript>");
            sb
.Append("<div style='width: 302px; height: 352px;'>");
            sb
.Append("<div style='width: 302px; height: 352px; position: relative;'>");
            sb
.Append("<div style='width: 302px; height: 352px; position: absolute;'>");
            sb
.Append("<iframe src='" + "https://www.google.com/recaptcha/api/fallback?k=" + Statics.reCAPTCHA.SiteKey + "'");
            sb
.Append("frameborder='0' scrolling='no'");
            sb
.Append("style='width: 302px; height:352px; border-style: none;'>");
            sb
.Append("</iframe>");
            sb
.Append("</div>");
            sb
.Append("<div style='width: 250px; height: 80px; position: absolute; border-style: none;");
            sb
.Append("bottom: 21px; left: 25px; margin: 0px; padding: 0px; right: 25px;'>");
            sb
.Append("<textarea id='g-recaptcha-response' name='g-recaptcha-response'");
            sb
.Append("class='g-recaptcha-response'");
            sb
.Append("style='width: 250px; height: 80px; border: 1px solid #c1c1c1;");
            sb
.Append("margin: 0px; padding: 0px; resize: none;' value=''>");
            sb
.Append("</textarea>");
            sb
.Append("</div>");
            sb
.Append("</div>");
            sb
.Append("</div>");
            sb
.Append("</noscript>");
           
return sb.ToMvcHtmlString();
       
}
   
}
}
namespace System.Web.Mvc
{
   
public class ReCaptchaModel
   
{
       
public bool success { get; set; }
       
public enum Theme
       
{
            light
,
            dark
       
}
   
}
   
public static class ReCaptchaValidate
   
{
       
public static async Task<bool> ValidateReCaptcha(this Controller controller, bool autoAddModelStateError = true)
       
{
           
var recaptchaResponse = controller.Request.Form["g-recaptcha-response"];
           
bool succses = false;
           
if (!recaptchaResponse.IsNullOfEmpty())
               
using (var client = new HttpClient())
               
{
                    client
.BaseAddress = new Uri("https://www.google.com/recaptcha/");
                    client
.DefaultRequestHeaders.Accept.Clear();
                    client
.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
                   
// New code:
                   
HttpResponseMessage response = await client.GetAsync("api/siteverify?secret=" + Config.reCAPTCHA.SecretKey + "&response=" + recaptchaResponse);
                   
if (response.IsSuccessStatusCode)
                   
{
                       
ReCaptchaModel CaptchResponse = await response.Content.ReadAsAsync<ReCaptchaModel>();
                        succses
= CaptchResponse.success;
                   
}
                   
else
                        succses
= false;
               
}
           
if (!succses && autoAddModelStateError)
                controller
.ModelState.AddModelError("Captcha", LangRess.PleaseProveYouAreHumain);
           
return succses;
       
}
   
}
}

to aply it on the view:
just use @Html.ReCaptcha()
@using (Html.BeginForm())
{
   
@Html.AntiForgeryToken()
   
<input type="email" name="Email" />
   
   
@Html.ReCaptcha()
   
   
<button type="submit">Send!</button>
}

then validate in the controller, with or without ModelState Error:
        [HttpPost, ValidateAntiForgeryToken]
       
public async Task<ActionResult> Captcha(string email)
       
{
           
//1)With ModelState
           
var valide = await ((Controller)this).ValidateReCaptcha();
           
if (ModelState.IsValid)
               
return View("Succses"); //a human is confirmed!
           
return View(); //Fail, return the view to display modelstate error
 
           
//2)Without ModelState
           
var isValide = await ((Controller)this).ValidateReCaptcha(autoAddModelStateError: false);
           
if (isValide)
               
{ /*succses*/ }
           
else
               
{ /*fail*/}
       
}





Tahir Khalid

unread,
Dec 10, 2014, 11:27:55 AM12/10/14
to reca...@googlegroups.com
Thanks Benoit, exactly what I was looking for.  Just one question, is this for the "new" Google ReCaptcha?

Thanks,

T

Tahir Khalid

unread,
Dec 11, 2014, 4:41:28 AM12/11/14
to reca...@googlegroups.com
Hey worked great, still not sure how the new one works but it does haha

tuzemec

unread,
Dec 18, 2014, 7:09:05 AM12/18/14
to reca...@googlegroups.com

Either I'm doing something wrong or you are hiding the captcha when it fails to validate (or the user just leave it untouched).
And I'm not sure that this is a good behaviour.
...

Tahir Khalid

unread,
Dec 18, 2014, 7:11:24 AM12/18/14
to reca...@googlegroups.com
use the following client side code to reset the control (or put it into the extension where the HTML is built):

grecaptcha.reset();

tuzemec if you look in the main group I have posted a guide on how to implement the google reCAPTCHA in an MVC 4 project (adapting Benoit's code).

Cheers,

T

tuzemec

unread,
Dec 18, 2014, 7:15:42 AM12/18/14
to reca...@googlegroups.com
Yeah, sorry - it's my bad.
I just found out why it's hidden for me when the model invalidates and I was about to delete my post :-)

Thanks for the quick reply :-)
Reply all
Reply to author
Forward
0 new messages