gpt4 book ai didi

c# - 使用自定义 ValidationResult 处理数据注释验证

转载 作者:行者123 更新时间:2023-11-30 16:18:46 25 4
gpt4 key购买 nike

我有一个像这样的自定义 ValidationAttribute :


public class ReceiverRegion : ValidationAttribute
{
private RegionService regionService;
private CityService cityService;

public ReceiverRegion() : base("Incorrect region code")
{
this.regionService = new RegionService();
this.cityService = new CityService();
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int regionId = Convert.ToInt32(value);
int plate = Convert.ToInt32((validationContext.ObjectInstance as CorporateOrderItem).ReceiverCity);

int productGroupId = Convert.ToInt32(validationContext.Items["productGroup"].ToString());

if (!CheckReceiverRegionExistence(regionId, plate, productGroupId))
{
IEnumerable regions = this.regionService.GetList(cityService.GetByPlate(plate).PKCityId);

return new CorporateOrderValidationResult(base.ErrorMessage, regions.Select(r=>r.Name));
}
return <b>CorporateOrderValidationResult.Success</b>;
}

private bool CheckReceiverRegionExistence(int plate, int regionId, int productGroup)
{
return !(regionService.GetByCityAndRegionIdForProductGroup(plate, regionId, productGroup) == null);
}
}

But as you can see in IsValid method, I'm trying to return a custom object which inherits from ValidationResult. My problem is, I can't access the extra members of my CorporateOrderValidationResult instance since IsValid returns the base ValidationResult type. Below is the code where I call validate and get a collection of ValidationResult as return value.


List results = new List();
bool isValid = Validator.TryValidateObject(instance, context, results, true);

我试图将结果对象转换为 List<CorporateOrderValidationResult> ,但无论我尝试什么(例如 --> item as CorporateOrderValidationResultresults.OfType<CorporateOrderValidationResult>()(CorporateOrderValidationResult)item) 我要么得到 InvalidCastException 要么 null 值。是否有可能将此结果列表转换为我的自定义结果列表类?谢谢...

最佳答案

我试图重现此行为,但一切都按预期进行:

public class TestClass
{
[TestValidation]
public string TestProp { get; set; }
}

public class TestValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return new TestResult();
}
}

public class TestResult : ValidationResult
{
public TestResult()
: base("test")
{
}
}

验证代码:

var instance = new TestClass();
var context = new ValidationContext(instance, null, null);
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(instance, context, results, true);
//Contains one instance of TestResult
var customResults = results.OfType<TestResult>().ToArray();

关于c# - 使用自定义 ValidationResult 处理数据注释验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15903316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com