我正在尝试找到一种合适的方法来验证POST和PUT请求。我想出了两种方法,“ Validate()”和“ ValidateAsync()”。我只是不确定该使用哪个。
'Validate()',一种同步方法,返回“ yield return”,并带有async.Result(无等待)查询,据我所知,它与sync(除非我错了并且它是异步的):
public IEnumerable<ValidationResult> Validate(Entity entity)
{
// ** NOTE: NO AWAIT AND USING '.RESULT' TO GET VALUE.**
var idExistsAsync = repo.ExistsAsync(e => e.Id == entity.Id).Result;
if (!idExistsAsync)
yield return new ValidationResult("Id does not exist");
// ** NOTE: NO AWAIT AND USING '.RESULT' TO GET VALUE.**
var userNameExistsAsync = repo.ExistsAsync(e => e.UserName == entity.UserName).Result;
if (!userNameExistsAsync)
yield return new ValidationResult("UserName does not exist");
}
var idExists = repo.Exists(e => e.Id == entity.Id);
var userNameExists = repo.Exists(e => e.UserName == entity.UserName);
'ValidateAsync()',一种异步方法,但是没有'yield return',将'errors'添加到列表中并返回List():
public async Task<IEnumerable<ValidationResult>> ValidateAsync(Entity entity)
{
var result = new List<ValidationResult>();
var idExistsAsync = await repo.ExistsAsync(e => e.Id == entity.Id);
if (!idExistsAsync)
result.Add(new ValidationResult("Id does not exist"));
var userNameExistsAsync = await repo.ExistsAsync(e => e.UserName == entity.UserName);
if (!userNameExistsAsync)
result.Add(new ValidationResult("UserName does not exist"));
return result;
}
谢谢。