Deserialize a date query parameter of the form yyyy-MM-dd into a noda time LocalDate object using ASP.NET Web API

冷暖自知 提交于 2019-12-04 03:28:32

Thanks to this very helpful article from Microsoft, I was able to find the solution using a custom model binder.

Add this class to your project:

public class LocalDateModelBinder : IModelBinder
{
    private readonly LocalDatePattern _localDatePattern = LocalDatePattern.IsoPattern;

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof (LocalDate))
            return false;

        var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (val == null)
            return false;

        var rawValue = val.RawValue as string;

        var result = _localDatePattern.Parse(rawValue);
        if (result.Success)
            bindingContext.Model = result.Value;

        return result.Success;
    }
}

Then change your controller method to use it.

public LocalDate GetPeopleByBirthday(
    [ModelBinder(typeof(LocalDateModelBinder))] LocalDate birthday)

The article also mentions other ways to register model binders.

Note that since your method returns a LocalDate, you'll still need the Noda Time serialziation for Json.net, as that ends up getting used in the body for the return value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!