问题描述
我正在使用此代码在我的ASP.Net MVC 5页面上实现Google的reCaptcha:
https://www.c-sharpcorner.com/blogs/google-recaptcha-in-asp-net-mvc
public class ValidateGoogleCaptchaAttribute : ActionFilterattribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
const string urlToPost = "https://www.google.com/recaptcha/api/siteverify";
var captchaResponse = filterContext.HttpContext.Request.Form["g-recaptcha-response"];
if (string.IsNullOrWhiteSpace(captchaResponse)) AddErrorAndRedirectToGetAction(filterContext);
var validateResult =
ValidateFromGoogle(urlToPost,GoogleReCaptchaVariables.ReCaptchaSecretKey,captchaResponse);
if (!validateResult.Success) AddErrorAndRedirectToGetAction(filterContext);
base.OnActionExecuting(filterContext);
}
此代码的问题是,相关网站无法访问Internet,并且无法直接调用Google的API,它必须通过内部服务IReCaptcha,该服务通过Unity注入整个系统。 MVC:
container.RegisterType<IReCaptcha,ReCaptcha>();
问题是:如何将IReCaptcha注入ValidateGoogleCaptchaAttribute?
解决方法
似乎唯一的解决方案是获取当前的DependencyResolver并手动获取服务:
var reCaptcha = DependencyResolver.Current.GetService(typeof(IReCaptcha)) as IReCaptcha;
我相信这应该可以在任何地方使用。