ASP.NET Core 2中的ModelBinder和日期

时间:2017-11-21 13:59:09

标签: c# asp.net date asp.net-core-mvc asp.net-core-2.0

我的网址中的所有日期都采用以下格式:dd-MM-yyyy。示例:31-12-2017

目前,我的Web API有一个像这样的方法

[HttpGet]
public Task<IAsyncResult> GetSomething([FromQuery] date) 
{
    ...
}

问题是我的Web API似乎只适用于格式为美国英语的日期。

  • 12-31-2017 之类的日期将有效。
  • 31-12-2017 之类的日期将无效。

如何将我的自定义数据格式从查询绑定到注入的参数?

2 个答案:

答案 0 :(得分:2)

您可以使用自定义Model Binder来完成此操作。以下是示例代码:

public class DateTimeModelBinder : IModelBinder
{
    private readonly IModelBinder baseBinder = new SimpleTypeModelBinder(typeof(DateTime));

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult != ValueProviderResult.None)
        {
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

            var valueAsString = valueProviderResult.FirstValue;

            //  valueAsString will have a string value of your date, e.g. '31-12-2017'
            //  Parse it as you need and build DateTime object
            var dateTime = DateTime.ParseExact(valueAsString, "dd-MM-yyyy", CultureInfo.InvariantCulture);
            bindingContext.Result = ModelBindingResult.Success(dateTime);

            return Task.CompletedTask;
        }

        return baseBinder.BindModelAsync(bindingContext);
    }
}

[HttpGet]
public Task<IAsyncResult> GetSomething([FromQuery] [ModelBinder(typeof(DateTimeModelBinder))] date) 
{
    ...
}

答案 1 :(得分:1)

我在startup.cs中为ASP核心2.0提交了这个

            services.Configure<RequestLocalizationOptions>(
            opts =>
            {
                var supportedCultures = new List<CultureInfo>
                {

                        new CultureInfo("en-GB"),
                        new CultureInfo("ar")
                };


                opts.DefaultRequestCulture = new RequestCulture("en-GB");
                // Formatting numbers, dates, etc.
                opts.SupportedCultures = supportedCultures;
                // UI strings that we have localized.
                opts.SupportedUICultures = supportedCultures;
                opts.DefaultRequestCulture = new RequestCulture(culture: "en-GB", uiCulture: "en-GB");


            });

这将使模型绑定接受格式dd / MM / yyy