2017-05-30 95 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

相关问题