如何以数据对象数组的形式返回Web API响应

时间:2019-05-17 06:50:54

标签: c# .net json asp.net-web-api2

在我的WebAPI项目中,我有两个类名,分别为Header和Items,在Items类中,Quantity属性为小数。我正在使用数据注释来验证模型。每当我收到JSON请求,要求“数量”为“空”或“ NULL”或项目列表为负值时,我都需要从模型返回带有message和ItemNumbers作为数组的响应。

我可以获取该属性在DataANnotations中使用的错误消息,但无法获取该Items的模型值

string errors = JsonConvert.SerializeObject(ModelState.Values
                .SelectMany(state => state.Errors)
                .Select(error => error.ErrorMessage));

 My Header class is like 

 public class Header
 {
    [Required(ErrorMessage = "OrderNumber cannot be blank")]
    [Range(0, int.MaxValue, ErrorMessage = "OrderNumber Must 
      contain only numbers")]
    [StringLength(6, ErrorMessage = "OrderNumber cannot be more 
      than 6 characters")]
    public string OrderNumber { get; set; }
    public List<Items> Items { get; set; }
 }

 My Items class is like 

  public class Items
  {
    public string ItemNumber { get; set; }
    public string Description { get; set; }
    [Required(ErrorMessage = "Quantity cannot be blank")]
    public string Quantity { get; set; }
    public string T { get; set; }
  }

  And My Request as 

      {
         "OrderNumber": "12345",
         "Items": [
            {
                "ItemNumber": "9999",
                "Description": "ABCD",
                "Quantity": ,
                "T": "O"
            },
        {
                "ItemNumber": "9998",
                "Description": "EFGH",
                "Quantity": 7.1,
                "T": "O"
            }
            ]}

我希望输出应为如果我如上所述发送请求,则需要API响应为

 {
   "status": 400,
   "message": "Quantity cannot be blank",
       "data": [
             {
            "ItemNumber": "9999",
            "Quantity": ""
             }
             ],}

意味着我需要在项目列表中显示哪些项目的数量为空或空的响应。

0 个答案:

没有答案