''# fix SO code coloring issue.
<Extension()>
Public Function reCaptcha(ByVal htmlHelper As HtmlHelper) As MvcHtmlString
Dim captchaControl = New Recaptcha.RecaptchaControl With {.ID = "recaptcha",
.Theme = "clean",
.PublicKey = "XXXXXX",
.PrivateKey = "XXXXXX"}
Dim htmlWriter = New HtmlTextWriter(New IO.StringWriter)
captchaControl.RenderControl(htmlWriter)
Return MvcHtmlString.Create(htmlWriter.InnerWriter.ToString)
End Function
从这里开始,您需要一个可重用的服务器端验证器
Public Class ValidateCaptchaAttribute : Inherits ActionFilterAttribute
Private Const CHALLENGE_FIELD_KEY As String = "recaptcha_challenge_field"
Private Const RESPONSE_FIELD_KEY As String = "recaptcha_response_field"
Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)
If IsNothing(filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)) Then
''# this will push the result value into a parameter in our Action
filterContext.ActionParameters("CaptchaIsValid") = True
Return
End If
Dim captchaChallengeValue = filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)
Dim captchaResponseValue = filterContext.HttpContext.Request.Form(RESPONSE_FIELD_KEY)
Dim captchaValidtor = New RecaptchaValidator() With {.PrivateKey = "xxxxx",
.RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
.Challenge = captchaChallengeValue,
.Response = captchaResponseValue}
Dim recaptchaResponse = captchaValidtor.Validate()
''# this will push the result value into a parameter in our Action
filterContext.ActionParameters("CaptchaIsValid") = recaptchaResponse.IsValid
MyBase.OnActionExecuting(filterContext)
End Sub
上面这行代码是可重用的
下面是重复实现 reCaptcha 的容易程度
现在您已经有了可重用的代码... ... 所有您需要做的就是将验证码添加到您的视图中。
<%: Html.reCaptcha %>
当您将表单发送到控制器时..。
''# Fix SO code coloring issues
<ValidateCaptcha()>
<AcceptVerbs(HttpVerbs.Post)>
Function Add(ByVal CaptchaIsValid As Boolean, ByVal [event] As Domain.Event) As ActionResult
If Not CaptchaIsValid Then ModelState.AddModelError("recaptcha", "*")
'#' Validate the ModelState and submit the data.
If ModelState.IsValid Then
''# Post the form
Else
''# Return View([event])
End If
End Function
[HttpPost]
[ReCaptcha]
public ActionResult MyAction(MyModel model)
{
if (!ModelState.IsValid) // Will have a Model Error "ReCaptcha" if the user input is incorrect
return Json(new { capthcaInvalid = true });
... other stuff ...
}
// return ActionResult if you want
public string RecaptchaWork()
{
// Get recaptcha value
var r = Request.Params["g-recaptcha-response"];
// ... validate null or empty value if you want
// then
// make a request to recaptcha api
using (var wc = new WebClient())
{
var validateString = string.Format(
"https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
"your_secret_key", // secret recaptcha key
r); // recaptcha value
// Get result of recaptcha
var recaptcha_result = wc.DownloadString(validateString);
// Just check if request make by user or bot
if (recaptcha_result.ToLower().Contains("false"))
{
return "recaptcha false";
}
}
// Do your work if request send from human :)
}
[CaptchaValidator(
PrivateKey = "your private reCaptcha Google Key",
ErrorMessage = "Invalid input captcha.",
RequiredMessage = "The captcha field is required.")]
public ActionResult MyAction(myVM model)
{
if (ModelState.IsValid) //this will take care of captcha
{
}
}
或者
public ActionResult MyAction(myVM model, bool captchaValid)
{
if (captchaValid) //manually check for captchaValid
{
}
}
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)
{
...
ExampleView.cshtml
@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='@System.Configuration.ConfigurationManager.AppSettings["RecaptchaClientKey"]'></div>
</div>
<div class="row">
<input type="submit" id="submit-button" class="btn btn-default" value="Send Your Message" />
</div>
}
Recaptchaservices.cs
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; }
}
}
}
Web.config
<configuration>
<appSettings>
<!--recaptcha-->
<add key="RecaptchaSecret" value="***secret key from https://developers.google.com/recaptcha***" />
<add key="RecaptchaClientKey" value="***client key from https://developers.google.com/recaptcha***" />
</appSettings>
</configuration>