将 WebApi 路由参数中的刻度绑定到 DateTime

Binding ticks in a WebApi route parameter to DateTime

我的 DateTime 对象需要毫秒级精度,因此我从我的 Windows 服务向我的 WebApi 发送 Ticks。这是我对 api 的调用,最后一个参数是 datetime

v1/Product/2/1/1000/636149434774700000

在 Api 上,请求到达如下所示的控制器:

[Route("api/v1/Product/{site}/{start?}/{pageSize?}/{from?}")]
public IHttpActionResult Product(Site site, int start = 1, int pageSize = 100, DateTime? fromLastUpdated = null)

默认模型绑定器无法将刻度绑定到 DateTime 参数。如有任何提示,我们将不胜感激。

独立使用long fromLastUpdatedparse and cast to DateTime

[Route("api/v1/Product/{site}/{start?}/{pageSize?}/{from?}")]
public IHttpActionResult Product(Site site, int start = 1, int pageSize = 100, long? fromLastUpdated = null)
{
    if (fromLastUpdated.HasValue)
    {
        var ticks = fromLastUpdated.Value;
        var time = new TimeSpan(fromLastUpdated);
        var dateTime = new DateTime() + time;
        // ...
    }
    return ...
}
  1. 您可以通过以下路径调用它v1/Product/2/1/1000/2016-11-17T01:37:57.4700000。模型绑定将正常工作。

  2. 或者您可以定义自定义模型活页夹:

    public class DateTimeModelBinder : System.Web.Http.ModelBinding.IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(DateTime?)) return false;
    
            long result;
    
            if  (!long.TryParse(actionContext.RequestContext.RouteData.Values["from"].ToString(), out result)) 
                return false;
    
            bindingContext.Model = new DateTime(result);
    
            return bindingContext.ModelState.IsValid;
        }
    }
    
    [System.Web.Http.HttpGet]
    [Route("api/v1/Product/{site}/{start?}/{pageSize?}/{from?}")]
    public IHttpActionResult Product(Site site, 
                                     int start = 1, 
                                     int pageSize = 100,
                                     [System.Web.Http.ModelBinding.ModelBinderAttribute(typeof(DateTimeModelBinder))] DateTime? fromLastUpdated = null)   
    {
        // your code
    }