Last active
September 8, 2022 23:43
-
-
Save mcshaz/141b334efe08691a590170819e1f174a to your computer and use it in GitHub Desktop.
simple implementation of the Google reCAPTCHA service in C#/.Net MVC5 using async method (as oppsed to ActionFilterAttribute)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace MyMvcApp.Controllers | |
{ | |
public class HomeController : Controller | |
{ | |
[HttpPost] | |
[ValidateAntiForgeryToken] | |
public async Task<ActionResult> ContactSubmit( | |
[Bind(Include = "FromName, FromEmail, FromPhone, Message, ContactId")] | |
ContactViewModel model) | |
{ | |
if (!await RecaptchaServices.Validate(Request)) | |
{ | |
ModelState.AddModelError(string.Empty, "You have not confirmed that you are not a robot"); | |
} | |
if (ModelState.IsValid) | |
{ | |
... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@model MyMvcApp.Models.ContactViewModel | |
@*This is assuming the master layout places the styles section within the head tags*@ | |
@section Styles { | |
@Styles.Render("~/Content/ContactPage.css") | |
<script src='https://www.google.com/recaptcha/api.js'></script> | |
} | |
@using (Html.BeginForm("ContactSubmit", "Home",FormMethod.Post, new { id = "contact-form" })) | |
{ | |
@Html.AntiForgeryToken() | |
... | |
<div class="form-group"> | |
@Html.LabelFor(m => m.Message) | |
@Html.TextAreaFor(m => m.Message, new { @class = "form-control", @cols = "40", @rows = "3" }) | |
@Html.ValidationMessageFor(m => m.Message) | |
</div> | |
<div class="row"> | |
<div class="g-recaptcha" data-sitekey="***site key from https://developers.google.com/recaptcha***"></div> | |
</div> | |
<div class="row"> | |
<input type="submit" id="submit-button" class="btn btn-default" value="Send Your Message" /> | |
</div> | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using System.Web; | |
using System.Configuration; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using Newtonsoft.Json; | |
using System.Runtime.Serialization; | |
namespace MyMvcApp.Services | |
{ | |
public class RecaptchaServices | |
{ | |
//ActionFilterAttribute has no async for MVC 5 therefore not using as an actionfilter attribute - needs revisiting in MVC 6 | |
internal static async Task<bool> Validate(HttpRequestBase request) | |
{ | |
string recaptchaResponse = request.Form["g-recaptcha-response"]; | |
if (string.IsNullOrEmpty(recaptchaResponse)) | |
{ | |
return false; | |
} | |
using (var client = new HttpClient { BaseAddress = new Uri("https://www.google.com") }) | |
{ | |
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
var content = new FormUrlEncodedContent(new[] | |
{ | |
new KeyValuePair<string, string>("secret", ConfigurationManager.AppSettings["RecaptchaSecret"]), | |
new KeyValuePair<string, string>("response", recaptchaResponse), | |
new KeyValuePair<string, string>("remoteip", request.UserHostAddress) | |
}); | |
var result = await client.PostAsync("/recaptcha/api/siteverify", content); | |
result.EnsureSuccessStatusCode(); | |
string jsonString = await result.Content.ReadAsStringAsync(); | |
var response = JsonConvert.DeserializeObject<RecaptchaResponse>(jsonString); | |
return response.Success; | |
} | |
} | |
[DataContract] | |
internal class RecaptchaResponse | |
{ | |
[DataMember(Name = "success")] | |
public bool Success { get; set; } | |
[DataMember(Name = "challenge_ts")] | |
public DateTime ChallengeTimeStamp { get; set; } | |
[DataMember(Name = "hostname")] | |
public string Hostname { get; set; } | |
[DataMember(Name = "error-codes")] | |
public IEnumerable<string> ErrorCodes { get; set; } | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<configuration> | |
<appSettings> | |
<!--recaptcha--> | |
<add key="RecaptchaSecret" value="***secret from https://developers.google.com/recaptcha***" /> | |
</appSettings> | |
</configuration> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment