我以为我会尝试使用 Blazor 服务器端,到目前为止,我已经设法以一种或另一种方式克服了大多数令人头疼的问题,并享受它,直到现在。
我正在尝试为需要用户 IP 地址的 Google Recaptcha v3 编写验证器。通常我会得到 IHttpContextAccessor :
var httpContextAccessor = (IHttpContextAccessor)validationContext.GetService(typeof(IHttpContextAccessor));
但现在返回 null!我还发现尝试以相同方式获取 IConfiguration 失败,但为此,我可以在 Startup.cs 中创建一个静态属性。
这是一天工作中的最后一个障碍,这让我感到困惑。
关于如何将该 IP 地址放入验证器的任何想法?
谢谢!
编辑:
我刚刚发现使 httpContextAccessor 为空的错误!
((System.RuntimeType)validationContext.ObjectType).DeclaringMethodthrew 类型为“System.InvalidOperationException”的异常
这是验证器:
public class GoogleReCaptchaValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
Lazy<ValidationResult> errorResult = new Lazy<ValidationResult>(() => new ValidationResult("Google reCAPTCHA validation failed", new String[] { validationContext.MemberName }));
if (value == null || String.IsNullOrWhiteSpace(value.ToString()))
{
return errorResult.Value;
}
var configuration = Startup.Configuration;
string reCaptchResponse = value.ToString();
string reCaptchaSecret = configuration["GoogleReCaptcha:SecretKey"];
IHttpContextAccessor httpContextAccessor = validationContext.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("secret", reCaptchaSecret),
new KeyValuePair<string, string>("response", reCaptchResponse),
new KeyValuePair<string, string>("remoteip", httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString())
});
HttpClient httpClient = new HttpClient();
var httpResponse = httpClient.PostAsync("https://www.google.com/recaptcha/api/siteverify", content).Result;
if (httpResponse.StatusCode != HttpStatusCode.OK)
{
return errorResult.Value;
}
String jsonResponse = httpResponse.Content.ReadAsStringAsync().Result;
dynamic jsonData = JObject.Parse(jsonResponse);
if (jsonData.success != true.ToString().ToLower())
{
return errorResult.Value;
}
return ValidationResult.Success;
}
}