向邮递员api发送一个参数获取请求

时间:2016-06-28 16:43:40

标签: c# asp.net-mvc asp.net-web-api http-get postman

我有一个控制器来获取大于特定日期的项目数。存储库显示为:

    public Dictionary<int, int> GetAllComplaintsCount(DateTime start)
    {
        try
        {
            return _context.Checklists
                .Where(a => a.COMPLAINT.Received_DT > start)
                .GroupBy(a => a.MonitorEnteredEmpID)
                .ToDictionary(g => g.Key, g => g.Count());
        }
        catch (Exception ex)
        {
            _logger.LogError("Could not get am with checklist", ex);
            return null;
        }
    }

修改我已经包含了我的路由器,看它是否正确:

         app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "crams/{controller=Home}/{action=Index}/{id?}");
            routes.MapRoute(
                name: "route",
                template: "crams/{controller}/{action}/{start?}");
        });

问题如果没有启动参数,我可以通过邮递员获得http://localhost:8000/crams/api/counts。我不确定,如何通过邮递员合并日期,所以它只能拉出比开始更大的日期。

我已经尝试了

  

http://localhost:8000/crams/api/counts/2016-1-1   但它回来了。

2 个答案:

答案 0 :(得分:1)

  

/ api / counts / 2016-1-1返回为null

您的API是:

... GetAllComplaintsCount(DateTime start)

所以你的网址应该是:

/api/counts?start=2016-1-1

这将使用默认路由。由于你没有在你的问题中包含路由,我假设(鉴于症状)它是默认的:

/api/{controller}/{id}

即使用/api/counts/2016-1-1指定“2016-1-1”作为id参数,但您没有id参数,并且您没有为start指定值{1}},所以你得到null。

您可以添加路线

/api/{controller}/{start}

我刚刚创建了一个api:

    [HttpGet]
    public string Test(DateTime d)
    {
        return d.ToString();
    }

并通过邮递员打电话(虽然任何客户都会给出相同的结果)

http://localhost/api/../Test?d=2016-1-1

它返回了预期的“01/01/2016 00:00:00”

答案 1 :(得分:0)

您可以尝试将滴答传递给API

http://localhost:8000/crams/api/counts/636027305821590000

然后

public Dictionary<int, int> GetAllComplaintsCount(Int64 dateTicks)
    {
        try
        {
            var startDate = new DateTime(dateTicks);
            return _context.Checklists
                .Where(a => a.COMPLAINT.Received_DT > startDate)
                .GroupBy(a => a.MonitorEnteredEmpID)
                .ToDictionary(g => g.Key, g => g.Count());
        }
        catch (Exception ex)
        {
            _logger.LogError("Could not get am with checklist", ex);
            return null;
        }
    }

以下是有关如何从日期(使用JS)获取Ticks的信息

How to convert JavaScript date object to ticks

希望这会有所帮助: