使用MVC Foolproof Validation
时,是否可以进行自定义验证asynchronous
?我想在自定义验证中从DbSet
检索一个对象,以检查该对象是否存在。
这可能吗?如果没有,是否有解决办法可以达到相同的效果?
这是我的代码:
public class RequiredThumbnailAssetId : ModelAwareValidationAttribute
{
static RequiredThumbnailAssetId() { Register.Attribute(typeof(RequiredThumbnailAssetId)); }
public async override Task<bool> IsValid(object value, object container)
{
var model = (IGridViewItemWithAssetId)container;
if (model.thumbnailAssetId <= 0)
{
return false;
}
CanFindLocationDatabaseContext db = new CanFindLocationDatabaseContext();
Asset asset = await db.assets.FindAsync(model.thumbnailAssetId);
if (asset == null)
{
return false;
}
return true;
}
}
以下是我收到的错误:
&#39; CanFindLocation.CustomValidations.RequiredThumbnailAssetId.IsValid(对象, 对象)&#39;:返回类型必须是&#39; bool&#39;匹配被覆盖的成员 &#39; Foolproof.ModelAwareValidationAttribute.IsValid(object,object)&#39;
提前致谢。
答案 0 :(得分:0)
您可以使用帖子How would I run an async Task<T> method synchronously?中定义的类,然后将您需要的覆盖和异步调用分离为单独的方法。这将允许您从异步请求中调用同步覆盖。
public class RequiredThumbnailAssetId : ModelAwareValidationAttribute
{
static RequiredThumbnailAssetId() { Register.Attribute(typeof(RequiredThumbnailAssetId)); }
public async override Task<bool> CheckValid(object value, object container)
{
var valid = AsyncHelpers.RunSync<bool>(() => isValid(value,container));
return valid;
}
public override bool IsValid(object value, object container)
{
var model = (IGridViewItemWithAssetId)container;
if (model.thumbnailAssetId <= 0)
{
return false;
}
CanFindLocationDatabaseContext db = new CanFindLocationDatabaseContext();
Asset asset = await db.assets.FindAsync(model.thumbnailAssetId);
if (asset == null)
{
return false;
}
return true;
}