我會給驗證碼驗證的接口,或者是代表什麼,這是人類的驗證真的,所以像:
public interface IHumanValidator
{
///Checks validates that the currentuser is human and not a bot
bool Validate();
/// Returns the text to display if the validation fails
string ValidationFailText{get;}
}
您需要更改控制器在構造函數中接受IHumanValidator
(或者如果你必須的話)。然後改變你的方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (!m_humanValidator.Validate())
ModelState.AddModelError("recaptcha", m_humanValidator.ValidationFailText);
if (ModelState.IsValid)
{
//Code for register
}
}
然後我會注入這是基於驗證碼驗證到控制器的實現和驗證針對:
public class ReCaptchaHumanValidator : IHumanValidator
{
public bool Validate()
{
ReCaptcha.Validate(Constants.ReCaptchaPrivateKey)
}
public string ValidationFailText
{
get{return "Incorrect value, enter the text again.";}
}
}
然後,你可以注入用於測試的模擬驗證您可以根據測試將其配置爲返回有效或無效。
這也有一個好處,如果您決定更改爲另一種驗證形式而不是ReCaptcha,那麼您只需提供IHumanValidator的另一個實現,而不需要更改代碼中的其他任何內容。