首页 > 解决方案 > Making an HTTP request during a Fluent Validation Must call

问题描述

I have a validator with 3 rules. Two of them check simple properties on a string, and the third makes an HTTP call to an external REST API to validate some other data. The HTTP calls are being called synchronously and there is a slight delay between making the calls and when I

        RuleFor(item => item.SourcePath)
        .Must((parent, item) =>
        { 
          if (parent.RequiresValidation &&
              fileSystem.File.Exists(parent.SourcePath))
          {
             bool valid = IsValid(parent, out _xmlErrorMessage);

             return valid;
          }
          else
          {
            return true;
          }
          })
        .WithSeverity(Severity.Error)
        .WithMessage(_xmlErrorMessage);

Within IsValid, I have something like this:

 var httpResponse = client.PostAsync(_url, httpContent).Result;
 return httpResponse.IsSuccessStatusCode

I have some code o my UI that displays these validation errors. The other two rules all report fine. I find that the UI will update with the simple rules and then a second later, my breakpoint will hit in the .Must call. Is there any way I can block this until the HTTP call completes somehow?

标签: c#fluentvalidation

解决方案


您需要await调用 HTTP 客户端,这意味着您需要使用异步验证

RuleFor(item => item.SourcePath)
    .MustAsync((parent, item) =>
    { 
        if (parent.RequiresValidation &&
                fileSystem.File.Exists(parent.SourcePath))
        {
             bool valid = IsValid(parent, out _xmlErrorMessage);
    
             return valid;
        }
        else
        {
            return true;
        }
    })
    .WithSeverity(Severity.Error)
    .WithMessage(_xmlErrorMessage);

IsValid方法将需要返回一个Task<T>对象,其中T是该方法的返回类型。我猜这是布尔值:

private async Task<T> IsValid(...)
{
    await var httpResponse = client.PostAsync(_url, httpContent).Result;

    return httpResponse.IsSuccessStatusCode
}

推荐阅读