1

I need milisecond precision on my DateTime object therefore I am sending Ticks from my Windows Service to my WebApi. This is my call to api, the last parameter is the datetime

v1/Product/2/1/1000/636149434774700000

On the Api the request hits a controller that looks like this:

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

Default model binder fails to bind the ticks to the DateTime parameter. Any tips would be appreciated.

Ali Kareem Raja
  • 566
  • 1
  • 7
  • 21

2 Answers2

1

Use long fromLastUpdated parse and cast to DateTime independently

[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 ...
}
Community
  • 1
  • 1
Noneme
  • 816
  • 6
  • 22
0
  1. You can call it with the following route v1/Product/2/1/1000/2016-11-17T01:37:57.4700000. The model binding will work properly.

  2. Or you can define a custom model binder:

    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
    }
    
Andriy Tolstoy
  • 5,690
  • 2
  • 31
  • 30