我想在ASP.NET MVC 4應用程序中使用'Recaptcha for .NET'。我做了指示here。我用AJAX請求,通過下面的腳本登錄用戶:Recaptcha for .NET在AJAX請求中不起作用
$("[email protected] button[type=button]").click(function() {
var wrapper = $(this).parents("[email protected]");
wrapper.find(".has-error").removeClass("has-error");
var dto = {
Valid: true,
UserName: wrapper.find(".user-name").val(),
Password: wrapper.find(".password").val(),
Remember: wrapper.find(".remember").is(":checked"),
};
if (!validateUserName(dto.UserName)) {
dto.Valid = false;
wrapper.find(".user-name").addClass("has-error");
}
if (dto.Password.length < 6) {
dto.Valid = false;
wrapper.find(".password").addClass("has-error");
}
if (dto.Valid) {
$.ajax({
url: "/Account/AjaxLogin",
type: "post",
data: JSON.stringify(dto),
context: dto,
dataType: "json",
contentType: "application/json;charset=UTF-8",
cache: false,
statusCode: {
404: function() {
alert("page not found");
},
200: function() {
}
}
}).done(function (result) {
if (result) {
if (result.Succeed) {
window.location.reload();
} else {
$.map(result.Messages, function (item, index) {
alert(item);
});
}
}
}).fail(function() {
}).always(function() {
});
}
return false;
});
這裏是我的操作方法:
[HttpPost]
[AllowAnonymous]
public ActionResult AjaxLogin(string username, string password, bool remember)
{
ScriptResult scriptResult = new ScriptResult() { Succeed = true };
RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
scriptResult.Messages.Add("Incorrect captcha answer.");
scriptResult.Succeed = false;
}
else
{
var user = UserManager.Find(username, password);
if (user != null)
{
user.UserName = user.UserName.ToLower();
SignIn(user, remember);
}
else
{
scriptResult.Messages.Add(LocalizeHelper.GetLocalizeString("Invalid username or password."));
scriptResult.Succeed = false;
}
}
return Json(scriptResult);
}
當我填寫登錄表單(用戶名,密碼和驗證碼字段),然後點擊登錄按鈕,然後我得到了以下錯誤:
An exception of type 'System.InvalidOperationException' occurred in Recaptcha.Web.dll but was not handled in user code
Additional information: Recaptcha challenge field cannot be empty.
使用調試程序遍歷代碼,直到失敗。但是我沒有看到你通過AJAX請求傳遞任何驗證碼輸入。您只能傳遞'dto'值並且與錯誤消息相匹配:'Recaptcha質詢字段不能爲空'。 – Jasen