【问题标题】:Making an HTTP request during a Fluent Validation Must call在 Fluent Validation Must 调用期间发出 HTTP 请求
【发布时间】:2021-10-21 23:13:37
【问题描述】:

我有一个包含 3 条规则的验证器。其中两个检查字符串的简单属性,第三个对外部 REST API 进行 HTTP 调用以验证其他一些数据。 HTTP 调用是同步调用的,在调用和我之间有一点延迟

        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);

在 IsValid 中,我有这样的事情:

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

我的 UI 中有一些代码可以显示这些验证错误。其他两条规则都报告正常。我发现 UI 将使用简单的规则进行更新,然后一秒钟后,我的断点将在 .Must 调用中命中。有什么办法可以阻止它,直到 HTTP 调用以某种方式完成?

【问题讨论】:

    标签: c# fluentvalidation


    【解决方案1】:

    你需要await调用HTTP客户端,也就是说你需要使用async validation

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2020-07-22
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多