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.

2 Answers 2

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 ...
}
Sign up to request clarification or add additional context in comments.

Comments

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
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.