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

时间:2016-12-13 06:11:51

标签: c# rest datetime asp.net-web-api model-binding

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

  

V1 /产品/ 2/1 /636149434774700000分之1000

在Api上,请求命中一个如下所示的控制器:

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

默认模型绑定器无法将标记绑定到DateTime参数。任何提示将不胜感激。

2 个答案:

答案 0 :(得分:1)

独立使用long fromLastUpdated parsecast 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 :(得分:0)

  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
    }