如何在ActionFilterAttribute中注入依赖关系



我正在用这段代码在我的ASP.Net MVC 5页面上实现谷歌的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);
}

这个代码的问题是,有问题的网站无法访问互联网,无法直接调用谷歌的API,它必须通过内部服务IReCaptcha,该服务通过Unity.MVC:注入整个系统

container.RegisterType<IReCaptcha, ReCaptcha>();

问题是:如何将IReCaptcha注入ValidateGoogleCaptchaAttribute?

似乎唯一的解决方案是获取当前的DependencyResolver并手动获取服务:

var reCaptcha = DependencyResolver.Current.GetService(typeof(IReCaptcha)) as IReCaptcha;

我相信这在任何地方都适用。

最新更新