c# - 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?
解决方案
您需要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
}
推荐阅读
- javascript - 以编程方式将电子邮件添加到 Stripe Charge
- deep-learning - 为什么阿尔法零不会耗尽内存
- css - 在 laravel 5.8 中找不到样式表以导入错误 font-awsome
- flutter - 每当我尝试收听它时如何修复 Flutter 流退出
- php - 如何使用数据库中的数据计算 Total、Tax
- c# - 按值对 linq 结果进行分组,并对空值或无效值进行分组并进行计数
- css - Vue 不允许我生成网格模板列
- 8thwall-web - 8thWall Web(即集成在亚马逊 sumerian 浏览器应用程序中的 8thWall)能否成功进行基于标记的跟踪或标记识别?
- jquery - 结合 Wow.js 和 Slicebox.js 来创建动画滑块
- reactjs - ReactJS 上下文:通过上下文传递数组