反序列化格式为yyyy-MM-DD的日期查询参数为使用的ASP.NET Web API野田一时间对象LOCALDATE [英] Deserialize a date query parameter of the form yyyy-MM-dd into a noda time LocalDate object using ASP.NET Web API

查看:320
本文介绍了反序列化格式为yyyy-MM-DD的日期查询参数为使用的ASP.NET Web API野田一时间对象LOCALDATE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调查使用NodaTime的LOCALDATE更换现有使用的BCL的DateTime /的DateTimeOffset类。我们由于我们的DateTime的可以说是模棱两可的行为误解碰上了一些与我们的code时区的相关问题。

I'm investigating the use of NodaTime LocalDate to replace our existing use of of the BCL DateTime/DateTimeOffset classes. We have run into a number of timezone related issues with our code due to our misunderstanding of the arguably ambiguous behavior of DateTime.

要充分利用NodaTime我希望能够从我们的ASP.NET Web API 2网页形式YYYY-MM-DD的服务发送和接收的日期。我在正确的序列化到LOCALDATE YYYY-MM-DD取得了成功。但是我无法反序列化的日期查询,参数为LOCALDATE。该LocateDate始终是1970-01-01。

To fully leverage NodaTime I want to be able to send and receive dates from our ASP.NET Web API 2 web services of the form YYYY-MM-DD. I have had success in properly serializing LocalDate to YYYY-MM-DD. However I am unable to deserialize a date query parameter to a LocalDate. The LocateDate is always 1970-01-01.

这是我目前的原型code(约code为清楚起见删除):

Here is my current prototype code (some code removed for clarity):

PeopleController.cs

[RoutePrefix("api")]
public class PeopleController : ApiController
{
    [Route("people")]
    public LocalDate GetPeopleByBirthday([FromUri]LocalDate birthday)
    {
        return birthday;
    }
}

的Global.asax.cs

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // Web API configuration and services
        var formatters = GlobalConfiguration.Configuration.Formatters;
        var jsonFormatter = formatters.JsonFormatter;
        var settings = jsonFormatter.SerializerSettings;
        settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
        settings.Formatting = Formatting.Indented;
        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

我通过

http://localhost/api/people?birthday=1980-11-20

但是,在返回的是1970年踏入code 1月1日,我确认生日设置为1970-01-01。

However, what is returned is January 1, 1970. Stepping into the code I confirm that birthday is set to 1970-01-01.

如何配置序列化,这样在URL中作为查询参数(或元件)指定的日期可适当序列化为NodaTime LOCALDATE?

How can I configure the serialization such that the date specified in the URL as a query parameter (or path element) can be properly serialized into a NodaTime LocalDate?

推荐答案

感谢<一个href=\"http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api\"相对=nofollow>微软这非常有帮助的文章,我才能够使用自定义的模型绑定来找到解决方案。

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.

请注意,由于你的方法的返回的一个 LOCALDATE ,你仍然需要Json.net野田时间serialziation,作为最终在身体习惯于为返回值

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.

这篇关于反序列化格式为yyyy-MM-DD的日期查询参数为使用的ASP.NET Web API野田一时间对象LOCALDATE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆