2017-05-30 100 views
0

我有以下代碼:如何設置日期時間UTC種類爲的WebAPI的URL參數

[HttpGet] 
[Route("{startDateUtc:datetime}/{endDateUtc:datetime}/{pageNumber?}", Name = "MyRoute")] 
[ResponseType(typeof(List<string>))] 
public IHttpActionResult GetData(DateTime? startDateUtc, DateTime? endDateUtc, int pageNumber = 1) 
{ 
    HandleData(startDateUtc.Value, endDateUtc.Value, pageNumber); 
    return this.Ok(); 
} 

我嘗試使用以下網址:http://localhost:5555/MyRoute/2014-09-17T00:00:00Z/2014-09-18T00:00:00Z/1 的問題是,startDateUtc.ValueendDateUtc.Value有種property = DateTimeKind.Local。 我想在日期DateTimeKind.Utc種類。

有一些解決方案,例如:應用.ToUniversalTime()函數或實現過濾器,它將處理日期時間參數和呼叫.ToUniversalTime()。但這些都不好,因爲我需要通過所有項目來完成這些任務。

是否有可能以某種方式配置它Global.asax或實施在退出的日期時間URL參數的一些解析器將根據和公正的要求〔實施例.ToUniversalTime()功能?

回答

0

您可以指定一種UTC屬性爲您的日期時間

// Change the Kind property of the current moment to 
// DateTimeKind.Utc and display the result. 

    myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Utc); 
    Display("Utc: .............", myDt); 

// Change the Kind property of the current moment to 
// DateTimeKind.Local and display the result. 

    myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Local); 
    Display("Local: ...........", myDt); 

// Change the Kind property of the current moment to 
// DateTimeKind.Unspecified and display the result. 

    myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Unspecified); 
    Display("Unspecified: .....", myDt); 

你應該像

[HttpGet] 
    [Route("{startDateUtc:datetime}/{endDateUtc:datetime}/{pageNumber?}", Name = "MyRoute")] 
    [ResponseType(typeof(List<string>))] 
    public IHttpActionResult GetData(DateTime? startDateUtc, DateTime? endDateUtc, int pageNumber = 1) 
    { 
    HandleData(DateTime.SpecifyKind(startDateUtc.Value, DateTimeKind.utc), DateTime.SpecifyKind(endDateUtc.Value, DateTimeKind.utc), pageNumber); 
    return this.Ok(); 
    } 
+0

呀,但是這就像使用ToUniversalTime()函數相同。我有大約20個其他控制器,並希望對這些也有相同的行爲。這意味着我將這個修補程序應用於其他20個控制檯X內部的3-4個路線:)太多的工作。想要有一個入口點來處理日期。 – Alexander

+0

爲什麼你不寫一個通用的方法來轉換它UTC只是通過日期時間在那裏你轉換爲特定的種類。 –

+0

因爲然後我需要將其粘貼到所有動作中。而其他想要添加新控制器的開發者需要這樣做。理想情況下,我想內置解析URL的日期時間和修復日期時間,或者如果它存在使用一些標誌爲此。例如..對於JSON體解析有一個標誌:GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling。如果我的taks有相同的東西,那將會很酷。 – Alexander

相關問題