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

发布于 2025-01-10 13:43:56 字数 1846 浏览 0 评论 0原文

我正在尝试使用 Fluent Validation 来验证 JSON 对象列表。我参考了官方文档 https://docs.fluidation.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"
}

]
}

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

I am trying to validate a list of JSON objects using Fluent Validation. I referred the official documentation
https://docs.fluentvalidation.net/en/latest/collections.html
as well but my function is not able to validate list of json objects

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);

The result is that it is not validating and I returned the value of p is returned as null. I am not sure how to handle list of JSON objects with Fluent Validation.

My JSON string is of format:

{
"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"
}

]
}

Can anyone please help me and suggest what I am doing wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千年*琉璃梦 2025-01-17 13:43:56

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

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

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 数据

我在发布请求时看到了您的 JSON 数据,它具有不同的格式,如下所示。 (避免错误的 json 格式

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

结果:

在此处输入图像描述

在此处输入图像描述< /a>

Please follow the below workaround to fix your issue:

I am slightly modified your code for my better understanding.

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(
quot;jsonvalue: {p.data[1].I_Name},.....");
            ...
        }

Post Request Body Data

{
"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"
    }
    ]
}

Make sure you have used valid JSON data while post Request like above.

I saw your JSON Data while post Request it has a different format like below. (Avoid the incorrect format of json)

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

Results:

enter image description here

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文