如何在 C# 中使用 Fluent Validation 和 Azure Function 验证 JSON 对象的列表?

How to Validate a list of JSON Objects using Fluent Validation and Azure Function in C#?

我正在尝试使用 Fluent Validation 验证 JSON 对象列表。我参考了官方文档 https://docs.fluentvalidation.net/en/latest/collections.html 同样,但我的函数无法验证 json 个对象的列表

public class MyModel
    {
        public string _No { get; set; }
        public string _date { get; set; }
        public string expiry_date { get; set; }
        public string I_Name { get; set; }
}

public class MyModels
    {
        public List<MyModel> mymodel { get; set; } = new List<MyModel>();
            
    }



public class ModelValidator : AbstractValidator<MyModel>
    {
        public ModelValidator()
        {
            RuleFor(x => x._No).NotEmpty();
            RuleFor(x => x._date).NotEmpty();
        }
}


public class MyModelsValidator : AbstractValidator<MyModels>
    {  
       public ModelsValidator()  
        {
             RuleForEach(x => x.mymodel).SetValidator(new ModelValidator()); 
        }
    } 

main.cs

 public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)

Validators.MyModelsValidator val = new MyModelsValidator();

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

var p = JsonConvert.DeserializeObject<MyModels>(requestBody);

var results = await val.ValidateAsync(p);

结果是它没有验证,我返回的 p 值返回为 null。我不确定如何使用 Fluent Validation 处理 JSON 个对象列表。

我的 JSON 字符串格式为:

{
"Data":[
    {
"_No":"12345678"
,"_date":"2022-02-08"
,"_expiry_date": "2023-02-08"
, "I_Name" : "Sam"
},

{
"_No":"5587421"
,"_date":"2022-02-10"
,"_expiry_date": "2024-02-08"
, "I_Name" : "Tam"
}

]
}

任何人都可以帮助我并指出我在这里做错了什么吗?

请按照以下解决方法解决您的问题:

为了更好地理解,我稍微修改了您的代码。

MyModel.cs class

 public class MyModel
    {
        public string _No { get; set; }
        public string _date { get; set; }
        public string _expiry_date { get; set; }
        public string I_Name { get; set; }
    }

    public class RootModels
    {
        public List<MyModel> data { get; set; }
    }

    public class ModelValidator : AbstractValidator<MyModel>
    {
        public ModelValidator()
        {
            RuleFor(x => x._No).NotEmpty();
            RuleFor(x => x._date).NotEmpty();
            RuleFor(x => x._expiry_date).NotEmpty();
            RuleFor(x => x.I_Name).NotEmpty();
        }
    }

    public class MyModelsValidator : AbstractValidator<RootModels>
    {
        public MyModelsValidator()
        {
            RuleForEach(x => x.data).NotNull().SetValidator(new ModelValidator());
        }
    }

Function.cs

 public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,ILogger log)
        {
            MyModelsValidator val = new MyModelsValidator();
            //Reading Request Body from post request
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            //Deserializeing Json Object
            var p = JsonConvert.DeserializeObject<RootModels>(requestBody);
            //Validating the Json Object
            var results = await val.ValidateAsync(p);
            //Check the result is valid or not
            if(results.IsValid == true)
            {
                log.LogInformation("The json object is valid");
            }
            log.LogInformation($"jsonvalue: {p.data[1].I_Name},.....");
            ...
        }

Post 请求正文数据

{
"Data":[
    {
        "_No":"12345678",
        "_date":"2022-02-08",
        "_expiry_date": "2023-02-08",
        "I_Name" : "Sam"
    },
    {
        "_No":"5587421",
        "_date":"2022-02-10",
        "_expiry_date": "2024-02-08",
        "I_Name" : "Tam"
    }
    ]
}

确保你使用了有效的JSON数据而post请求如上。

我看到了您的 JSON 数据,而 post 请求它具有如下所示的不同格式。 (避免格式不正确json)

"_No":"12345678"
,"_date":"2022-02-08"
,"_expiry_date": "2023-02-08"
, "I_Name" : "Sam"
},

结果: