2016-06-28 113 views
0

我有一個控制器來獲得大於某個日期的項目數。發送一個參數到郵遞員API獲取請求

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 但它回來空。

+0

將日期作爲字符串傳遞並在動作中解析它。 – Jasen

+0

@Jasen這是默認的模型綁定器所做的 –

回答

1

/API /計數/ 2016年1月1日回來爲空

您的API是:

... GetAllComplaintsCount(DateTime start) 

所以您的網址應該是:

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

這將與默認路由。正如你所不包含在你的問題的路由,我認爲(給出的症狀),它的默認:

/api/{controller}/{id} 

即使用/api/counts/2016-1-1規定「2016年1月1日」作爲id參數,但你不沒有id參數,並且您沒有爲start指定值,所以您會得到空值。

您可以添加路由作爲

/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」

+0

我感謝您的深思熟慮的答案!我試圖在我的默認路線下添加一條路線並將其命名爲路線,現在我的路線如下所示:app.UseMvc(routes => { } routes.MapRoute( name:「default」, template:「crams/{controller = Home}/{action = Index}/{id?}「); routes.MapRoute( name:」route「, template:」crams/{controller}/{action}/{start?} 「); }); – epv

+0

然後我用你的測試看看它是否會工作:所以我添加了測試httpget,但是當我運行「http:// localhost:8000/crams/api/counts/Test?d = 2016-1-1」時,我找不到404!你能告訴我,如果我在任何地方犯了錯誤嗎? – epv

+0

首先 - 用'../ counts?start = 2016-1-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)

的信息

How to convert JavaScript date object to ticks

希望這有助於:

+0

只是想知道,你試過嗎? –

+0

對不起,我現在沒有.net env來測試...你有錯誤嗎?我已經發送DateTime params之前應用程序使用蜱或特定的格式字符串,並使用.ParseExact ...如果我的代碼示例有錯誤,我可以更新它 –

+0

問題是路由不符合參數名字 - 在這裏也是如此。 –