我正在尝试创建多个自定义验证器来验证不同的类,并使用验证错误和类将它们组合成 JSON 响应。
我试图实现的 JSON 响应格式如下
{
"meta": {
"apiVersion": "1.0"
},
"data": {
"customer": {
"title": "Title",
"firstName": "FNAME",
"lastName": "LNAME",
"email": "EMAIL"
}
},
"errors": {
"error": {
"code": "CODE",
"message": "MESSAGE",
"value": "VALUE"
},
"customer": {
// this is dynamic depending on the validation results
"firstName": {
"code": "CODE",
"message": "MESSAGE",
"value": "VALUE"
},
// this is dynamic depending on the validation results
"LastName": {
"code": "CODE",
"message": "MESSAGE",
"value": "VALUE"
}
}
}
}
下面给出了我尝试使用的 C# 代码:
Meta meta = new Meta();
meta.apiVersion = "1.0";
Errors error2 = new Errors();
RootObject rObject = new RootObject();
Data data = new Data();
Customer cust = new Customer();
cust.title = "Mr";
cust.firstName = "Bob";
cust.lastName = "Joel";
cust.email = "test794@yahoo.com";
data.customer = cust;
rObject.meta = meta;
rObject.data = data;
var context = new ValidationContext(rObject.data.customer, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isVALID = Validator.TryValidateObject(rObject.data.customer,
context, results,
validateAllProperties: true);
if (results.Count > 0)
{
foreach (var error in results)
{
dynamic t = null;
foreach (var mem in error.MemberNames)
{
t = mem.ToString();
}
t.message = error.ErrorMessage;
rObject.errors = t;
}
}
var json = JsonConvert.SerializeObject(rObject, Formatting.Indented);
我不确定我是否朝着正确的方向前进,因为我主要面临的问题是在依赖于 ValidationResults 的错误对象中。因此,如果存在验证错误,我foreach
会通过它们进行检查,但主要问题是如何根据给出错误的字段名称创建一个对象,然后在其中添加错误消息。
因此,如果名字有错误,我需要创建一个名为名字的对象,依此类推。