如何在restful web api中传递List对象的类

时间:2016-11-16 12:47:51

标签: c# json rest serialization asp.net-web-api

我需要在restful web api中传递class的list对象。但我在web api中收到null值。 下面是我在Web API中的代码。

    Public class RequestDto
    {
      private string _clientId;
      public string ClientId
      {
          get { return _clientId; }
          set { _clientId= value; }
      }
      private List<DeliveryDocument> _deliveryDocumentInfo;
      public List<DeliveryDocument> DeliveryDocumentInfo
      {
          get { return _deliveryDocumentInfo; }
          set { _deliveryDocumentInfo = value; }
      }   
    }        
    public class DeliveryDocument
    {
       public string DocumentName { get; set; }
       public string DocumentURL { get; set; }
    }

public HttpResponseMessage PostSaveManifest([FromBody] RequestDto manifestRequest)
        {
//here i am receiving null value in list parameter
}

下面是调用web api的代码。

var values = new JObject();
values.Add("ClientId", "23824");

var DeliveryDocumentInfo = new List<DeliveryDocument>();
DeliveryDocumentInfo.Add(new DeliveryDocument { DocumentName = "Document Name", DocumentURL = "D:/Documnet/test.png" });
var serOut = JsonConvert.SerializeObject(DeliveryDocumentInfo);
values.Add("DeliveryDocumentInfo", serOut);

HttpContent content = new StringContent(values.ToString(), Encoding.UTF8, "application/json");
                var responsesss = client.PostAsync(Constants.URLValue + "/api/Manifest", content).Result;

2 个答案:

答案 0 :(得分:2)

在Web API中创建RequestDto的对象。根据 OrenHaliva 评论。

var manifest = new RequestDto();
manifest.ClientId = "23824";

var DeliveryDocumentInfo = new List<DeliveryDocument>();

DeliveryDocumentInfo.Add(new DeliveryDocument { DocumentName = "Document Name", DocumentURL = "D:/Documnet/test.png" });

manifest.DeliveryDocumentInfo = DeliveryDocumentInfo;

var serOut = JsonConvert.SerializeObject(manifest);
HttpContent content = new StringContent(serOut, Encoding.UTF8, "application/json");

var responsesss = client.PostAsync(Constants.URLValue + "/api/Manifest", content).Result;

答案 1 :(得分:0)

您发送的内容无法序列化为RequestDto类型。 “values”是一个列表,它位于你的Dto对象中,但你的api正在期待dto对象,而不仅仅是它里面的列表。