【问题标题】:How to pass class of List object in restful web api如何在restful web api中传递List对象的类
【发布时间】:2017-03-30 16:13:38
【问题描述】:

我需要在 restful web api 中传递类的列表对象。但我在 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;

【问题讨论】:

  • 您是否尝试过创建 RequestDto 而不是像您那样创建作业对象?
  • 不,我不这样做..但我会尝试..
  • @OrenHaliva 与 RequestDto 对象一起工作。谢谢
  • 这是因为您在序列化时将集合作为字符串传递给JObject。 serOut 看起来像"DeliveryDocumentInfo" : "[{}]"。这就是为什么解析时集合为空的原因。但是您已经找到了解决方法,所以一切都很好。只是想让您知道错误在哪里。

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


【解决方案1】:

在 Web API 中创建 RequestDto 对象。根据 OrenHaliva cmets.

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;

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 不是那样...我只传递了单个 RequestDto 对象,但在 RequestDto 对象下我传递了文档列表。
    猜你喜欢
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    相关资源
    最近更新 更多