对象没有从JSON主体传递给方法

时间:2017-11-27 11:08:00

标签: c# json asp.net-web-api2

我正在尝试运行我在MVC API中创建的方法,该方法需要通过JSON格式的主体将对象传递给它。据我所知,方法或对象没有错误,但我发送的JSON实际上并没有传递给方法,而且object参数保持为null。

这是方法:

 // Consignment Search
[HttpPost]
[ResponseType(typeof(Legacy.JobTracking))]
[Route("api/search/")]
public IHttpActionResult SearchConsignment(ConsignmentSearch search)
{ 
    // Get the ID
    var UserId = 0;
    using (_PortalDb)
    {
        var User = _PortalDb.PortalUsers.FirstOrDefault(u => u.ServerUser == search.User);
        if (User != null) UserId = User.UserId;
    }
    List<Legacy.JobTracking> Consignments;
    if (!ModelState.IsValid) return BadRequest("Invalid Search");
    if (search.JobNo == null && search.CustRef == null && search.ConRef == null && search.DateFrom == null && search.DateTo == null) return BadRequest("No search filters");
    if (search.JobNo != null)
    {
        // Run Job number search and continue
        Consignments = Legacy.Exporter.GetJobByNo(search.JobNo, search.User, search.Account, UserId);
    }
    else if (search.ConRef != null)
    {
        // Run Con Ref Search and continue
        Consignments = Legacy.Exporter.GetJobByCon(search.ConRef, search.User, search.Account, UserId);
    }
    else if (search.CustRef != null)
    {
        // Run Customer Ref Search and continue
        Consignments = Legacy.Exporter.GetJobByRef(search.CustRef, search.User, search.Account, UserId);
    }
    else if (search.DateFrom != null && search.DateTo != null)
    {
        // Run Date Range Search and continue
        Consignments = Legacy.Exporter.GetJobsInDateRange(search.DateTo, search.DateFrom, search.User, search.Account, UserId);
    }
    else
    {
        return BadRequest("Invalid Date Search");
    }
    return Ok(Consignments);
}

班级:

public class ConsignmentSearch
{
    public string JobNo;
    public string CustRef;
    public string ConRef;
    public string DateFrom;
    public string DateTo;
    public string User;
    public string Account;
}

身体中的JSON:

["consignmentSearch": {
  "dateFrom": "20150101",
  "dateTo": 20160101,
  "user": "LianeS",
  "account": "PORTAL"
}]

1 个答案:

答案 0 :(得分:1)

您在请求正文中传递的文本无效JSON(当然也不代表您的模型)。适用于您案例的有效JSON类似于:

{
  "dateFrom": "20150101",
  "dateTo": 20160101,
  "user": "LianeS",
  "account": "PORTAL"
}