如何将对象列表发送到webapi c#?

时间:2017-03-07 09:08:21

标签: c# asp.net-web-api

我正在尝试以json-array格式向webapi发送对象列表。但是,在参数中它变为null。

现在,让我发布到目前为止我尝试过的代码

[HttpPost]
        [Route("~/api/visitsave")]
        public IHttpActionResult Save(List<VisitDataModel> visitobj)
        {
            foreach (VisitDataModel visitobjs in visitobj) {
            VisitManager obj = new VisitManager(visitobjs);
            bool value = obj.Save();
        }
            return Ok();
        }

这是我试图传递的json数组,但它在参数visitobj中不起作用。

收到null。由于我是webapi和c#的新手,我正在努力解决这个问题 但是当我传递单个json对象时,我正在获取值,当我切换回列表时,它不起作用。

让我发布试图发布的json数组:

{"visitobj":[{"Remarks":"test","UserID":193,"FindingsAtSite":"nothing","CheckInDate":"2017-02-01 12:00:00","CheckOutDate":"2017-02-01 12:00:00","VisitStatusID":1,"CreatedBy":192,"CreatedDateTime":"2017-02-01 12:00:00","Claim":{"TransportMode":1,"Date":"2017-02-01 12:00:00","FromLocation":"chennai","ToLocation":"re","Ticket":123.2,"Conveyance":123.5,"Lodge":234.0,"Meals":23}}]}

这是jsonresponse我试图发送到我的webapi可以有人帮助这可能是一个愚蠢的问题,但我正在努力与此。在此先感谢!!

2 个答案:

答案 0 :(得分:1)

这是正常行为,因为您的合约不匹配。

将您的参数更改为以下内容,您的参数将正常

public class Claim
{
    public int TransportMode { get; set; }
    public string Date { get; set; }
    public string FromLocation { get; set; }
    public string ToLocation { get; set; }
    public double Ticket { get; set; }
    public double Conveyance { get; set; }
    public double Lodge { get; set; }
    public int Meals { get; set; }
}

public class Visitobj
{
    public string Remarks { get; set; }
    public int UserID { get; set; }
    public string FindingsAtSite { get; set; }
    public string CheckInDate { get; set; }
    public string CheckOutDate { get; set; }
    public int VisitStatusID { get; set; }
    public int CreatedBy { get; set; }
    public string CreatedDateTime { get; set; }
    public Claim Claim { get; set; }
}

public class VisiteRequest
{
     public List<Visitobj> visitobj { get; set; }
}

或者第二个选项是你必须将Json发送的对象更改为数组

[{"Remarks":"test","UserID":193,"FindingsAtSite":"nothing","CheckInDate":"2017-02-01 12:00:00","CheckOutDate":"2017-02-01 12:00:00","VisitStatusID":1,"CreatedBy":192,"CreatedDateTime":"2017-02-01 12:00:00","Claim":{"TransportMode":1,"Date":"2017-02-01 12:00:00","FromLocation":"chennai","ToLocation":"re","Ticket":123.2,"Conveyance":123.5,"Lodge":234.0,"Meals":23}}]

答案 1 :(得分:0)

可能是你以错误的格式传递json。我有像这样的API动作

[HttpPost]
[Route("sample")]
public IHttpActionResult SampleOp(List<SampleObj> smpJson)
{
      foreach (var item in smpJson){
          //Do Some Thing Here 
      }
      return ok();
}

将json数据传递为

[{
    "name":"name 1",
    "address":"address 1",
    "age":1
}, 
{
    "name":"name 2",
    "address":"address 2",
    "age":2
}]

这是我的SampleObj模式

public class SampleObj {
        public string name { get; set; }
        public string address { get; set; }
        public int age { get; set; }
    }

经过测试并在此工作