在ASP.NET MVC和Umbraco中集成Google reCAPTCHA并获取模型数据,可以按照以下步骤进行:
你可以通过NuGet安装 Microsoft.AspNet.Web.Optimization.React.GoogleReCaptcha
包:
Install-Package Microsoft.AspNet.Web.Optimization.React.GoogleReCaptcha
在你的Umbraco项目中,找到 Views
文件夹,然后在相应的视图中添加reCAPTCHA控件。例如,在 Login.cshtml
中:
@using React.Web.Mvc
@using Microsoft.AspNet.Web.Optimization.React.GoogleReCaptcha
<div class="form-group">
@Html.React("GoogleReCaptcha", new
{
sitekey = "YOUR_SITE_KEY"
})
</div>
在你的控制器中,添加逻辑来验证reCAPTCHA响应。例如,在 AccountController.cs
中:
using System.Web.Mvc;
using Umbraco.Core.Models;
using Umbraco.Web.Mvc;
public class AccountController : RenderController
{
public ActionResult Login()
{
return CurrentTemplate();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
// 验证reCAPTCHA
var recaptchaResponse = Request.Form["g-recaptcha-response"];
var isValid = VerifyRecaptcha(recaptchaResponse);
if (isValid)
{
// 处理登录逻辑
// ...
return RedirectToCurrentUmbracoPage();
}
else
{
ModelState.AddModelError("", "reCAPTCHA验证失败,请重试。");
}
}
return CurrentTemplate(model);
}
private bool VerifyRecaptcha(string response)
{
using (var client = new HttpClient())
{
var parameters = new Dictionary<string, string>
{
{ "secret", "YOUR_SECRET_KEY" },
{ "response", response }
};
var content = new FormUrlEncodedContent(parameters);
var result = client.PostAsync("https://www.google.com/recaptcha/api/siteverify", content).Result;
var json = result.Content.ReadAsStringAsync().Result;
dynamic data = JsonConvert.DeserializeObject(json);
return data.success;
}
}
}
创建一个模型来处理登录表单数据。例如,创建 LoginModel.cs
:
public class LoginModel
{
[Required]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
确保你的视图(例如 Login.cshtml
)绑定到模型:
@model YourNamespace.Models.LoginModel
@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Username)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="form-group">
@Html.React("GoogleReCaptcha", new
{
sitekey = "YOUR_SITE_KEY"
})
</div>
<button type="submit" class="btn btn-primary">登录</button>
}
运行你的项目并测试登录功能,确保reCAPTCHA正常工作并且能够正确验证用户输入。
通过以上步骤,你可以在ASP.NET MVC和Umbraco项目中成功集成Google reCAPTCHA,并在控制器中获取和处理模型数据。
领取专属 10元无门槛券
手把手带您无忧上云