I\'m trying to pass a UTC date as a query string parameter to a Web API method. The URL looks like
/api/order?endDate=2014-04-01T00:00:00Z&zoneId=4
So, for those of you who do not wish to override string-to-date conversion in your entire application, and also don't want to have to remember to modify every method that takes a date parameter, here's how you do it for a Web API project.
Ultimately, the general instructions come from here:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api#model-binders
Here's the specialized instructions for this case:
In your "WebApiConfig" class, add the following:
var provider = new SimpleModelBinderProvider(typeof(DateTime),new UtcDateTimeModelBinder());
config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
Create a new class called UtcDateTimeModelBinder:
public class UtcDateTimeModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext,
ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(DateTime)) return false;
var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (val == null)
{
return false;
}
var key = val.RawValue as string;
if (key == null)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName,
"Wrong value type");
return false;
}
DateTime result;
if (DateTime.TryParse(key, out result))
{
bindingContext.Model = result.ToUniversalTime();
return true;
}
bindingContext.ModelState.AddModelError(bindingContext.ModelName,
"Cannot convert value to Utc DateTime");
return false;
}
}