Suppose your application uses DateTime objects but only cares about the Date portion. With ASP.NET Web Api 2, building on ASP.NET MVC support, you can take control over how DateTime objects are serialized via c# attributes or configuration.
But suppose you don’t want to change global configuration? In other words, you’d like to change serialization only for a particular page?
My first attempt at this was to use the HttpContent extensibility point by deriving a class specialized for the kind of content (in this case, JsonContent) as described in detail here.
But it struck me that this was overkill since I wasn’t intending to change any of the response headers and only wanted to change a single entry point in the application.
Web API 2 controllers can return an object that implements IHttpActionResult. By implementing this it is possible to control the response body content (json) and thereby control serialization for a specific request. ApiController defines several helper methods that create IHttpActionResult objects for various scenarios (e.g., Ok() returns an OkResult).
The method I needed was Json<T>(). It has an overload that accepts a JsonSerializerSettings object. Setting JsonSerializerSettings.DateFormatString to a pattern that matches the pattern expected on the client side means that the desired DateTime info successfully roundtrips (even through other widgets, in this case, angularStrap’s datepicker).