How to pass class of List object in restful web ap

2019-09-15 01:06发布

问题:

I need to pass list object of class in restful web api. But i am receiving null value in web api. Below is my code in 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
}

Below code for calling 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;

回答1:

Create object of RequestDto in Web API. As per OrenHaliva comments.

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:

What you are sending cannot serialize into the RequestDto type. "values" is a list, which is in your Dto object but your api is expecting the dto object, not just the list inside of it.