私はMVCを初めて使用しています。私はreCAPTCHAをテストウェブサイトに追加して動作させていますが、ユーザがチェックボックスを選択したかどうかのチェックを含める必要があります。私はViewBagを介して別のメッセージを追加するのではなく、ウェブサイト上のすべてをきれいに保つために、@ html.ValidationSummaryリストに表示しないようにします。@ html.ValidationSummaryリストにreCAPTCHA検証エラーを追加するには
私はMVCプロジェクトテンプレートを作成しましたので、多くのコードは既にVS2013によって生成されています。したがって、私はこれをウェブサイトに統合する必要があります。また、マイクロソフトの例の1つは、コントローラーがアプリケーションフロー制御に関連するロジックのみを含む必要があるため、コントローラーでは実行しないことをお勧めしますが、コントローラーで行う方法を示しています。Microsoftは、 SMH)。
AccountController.cs
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
//Validate Google reCAPTCHA here
var response = Request["g-recaptcha-response"];
string secretKey = "SITE SECRET";
var client = new WebClient();
var recaptchaResult = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
var obj = JObject.Parse(recaptchaResult);
var status = (bool)obj.SelectToken("success");
//ViewBag.Message = status ? "Google reCaptcha validation success" : "Google reCaptcha validation failed";
if (ModelState.IsValid && status)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
Register.cshtmlキャプチャの検証が失敗したときに
@model WebApp1.Models.RegisterViewModel
@{
ViewBag.Title = "Register";
}
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="g-recaptcha" data-sitekey="SITE SECRET"></div>
<br />
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
@section Scripts {
<script type="text/javascript" src='https://www.google.com/recaptcha/api.js' async></script>
@Scripts.Render("~/bundles/jqueryval")
}
ありがとうございました。それはうまくいかなかった。コードのセクションは、ユーザーがチェックボックスをクリックした後にのみ実行されると思います。 –
@JWeezyコードのこのセクションは、ユーザーが送信をヒットした場合にのみ機能します。 'status'がfalseの場合、オブジェクトをただちに返さないのはなぜですか?' ModelState.AddModelError( ""、 "Captchaは入力されていません")の直後です。 'put' return View(model) '? –
これらの推奨事項は機能しましたが、期待通りにはできませんでした(テストケースの問題)。このチェックを残りのフォーム要素に埋め込みたいと思います。現在のところ、このチェックは他のフォームの検証がすべて完了したときにのみ起動します。たとえば、登録ページに移動し、何も記入せずに登録ボタンをクリックすると、電子メールとパスワードの検証だけが自動的に呼び出され、キャプチャは含まれません。しかし、キャプチャを完了せずに電子メールとパスワードを記入すると、エラーが発生します。どのようにこれを回避するための任意の考えですか? –