如何在Web API中管理POST请求

时间:2019-06-12 06:47:31

标签: c# rest model-view-controller

作为一个初学者,我在制作REST Web API程序时遇到麻烦。 我的客户端应用程序POST数据包含患者的实验室测试信息。 数据将是“患者”和“测试”信息各自的四个字段,但是每个患者的测试次数可以改变。

例如:接受1次检查的患者

    {
     "patientID": 1121,
     "patientName": "BOB",
     "age": "22",
     "gender": "male",
     "TestID": 10,
     "TubeCode": "GRN",
     "TestName": "HIV",
     "TestCode": "GRN-CHM",
    }

例如:接受2次检查的患者

   {
     "patientID": 1122,
     "patientName": "LINDA",
     "age": "26",
     "gender": "Female",
     "TestID": 12,
     "TubeCode": "GRN",
     "TestName": "HIV",
     "TestCode": "GRN-CHM",
     "TestID": 13,
     "TubeCode": "LAV",
     "TestName": "LFT",
     "TestCode": "LAV-CHM",
   }

例如:接受3次检查的患者

  {
     "patientID": 1123,
     "patientName": "HARI",
     "age": "29",
     "gender": "male",
     "TestID": 14,
     "TubeCode": "GRN",
     "TestName": "HIV",
     "TestCode": "GRN-CHM",
     "TestID": 15,
     "TubeCode": "LAV",
     "TestName": "LFT",
     "TestCode": "LAV-CHM",
     "TestID": 16,
     "TubeCode": "SPC",
     "TestName": "SPC1",
     "TestCode": "SPC-CHM",
    }

当客户端发布所有这些示例时,API必须能够接收此数据。

我尝试了许多方法,例如为测试信息添加列表对象。但是由于我的知识不足而无法完成。

     public void Post([FromBody] Patient_specimenInfo value)
     {           
      // I would like to know how can I manage the FROMBODY content here.
     }

我知道如何管理固定数量的患者和检查信息。但是这里的检查信息不是固定的。 我希望有人能给我最好的逻辑来处理这种情况。

3 个答案:

答案 0 :(得分:1)

您可以创建

之类的测试列表
public class Patient
{
  ...
  public List<Test> Tests{get;set;}
  .
  .
}

然后从客户端应用发送这样的json:

{
 "patientID": 1122,
 "patientName": "LINDA",
 "age": "26",
 "gender": "Female",
 "Tests":
 [
  {
  "TestID": 12,
  "TubeCode": "GRN",
  "TestName": "HIV",
  "TestCode": "GRN-CHM"
  },
  {
  "TestID": 13,
  "TubeCode": "LAV",
  "TestName": "LFT",
  "TestCode": "LAV-CHM"
  }
 ]
}

答案 1 :(得分:0)

通过乘法测试提供的Json格式不正确。您可以将Json数组用于测试。有关更多详细信息,请参见此链接https://www.w3schools.com/js/js_json_arrays.asp。 例如

{
 "patientID": 1123,
 "patientName": "HARI",
 "age": "29",
 "gender": "male",
 "Tests":[{
   "TestID": 14,
   "TubeCode": "GRN",
   "TestName": "HIV",
   "TestCode": "GRN-CHM"
  },
  {
   "TestID": 15,
   "TubeCode": "LAV",
   "TestName": "LFT",
   "TestCode": "LAV-CHM"
  }]
}

C#类如下所示:

public class Patient_specimenInfo
{
    ...
    public Test[] Tests { get; set;}
    ...
}

public class Test
{
    public int TestID {get; set; }
    public string TubeCode {get; set; }
    public string TestName {get; set; }
    public string TestCode {get; set; }
}

答案 2 :(得分:0)

代替使用

public void Post([FromBody] Patient_specimenInfo value)
{           
   // I would like to know how can I manage the FROMBODY content here.
}

请将其修改为

public void Post([FromBody] JObject value)
{           
      // here you can Convert the dynamic JObject to a Patient_specimenInfo object accordingly     
}