简体   繁体   English

ASP.NET Core 2 中的 ModelBinder 和日期

[英]ModelBinder and Dates in ASP.NET Core 2

All the dates in my URLs come in this format: dd-MM-yyyy .我的 URL 中的所有日期都采用以下格式: dd-MM-yyyy Example: 31-12-2017示例:31-12-2017

Currently, my Web API has a method like this目前,我的 Web API 有一个这样的方法

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

The problem is that my Web API seems work ONLY with dates formatted in US English .问题是我的 Web API 似乎只适用于美国英语格式的日期。

  • A date like 12-31-2017 will work.12-31-2017这样的日期将起作用。
  • Whereas a date like 31-12-2017 won't work.而像31-12-2017这样的日期是行不通的。

How can I make it bind my custom data format from the query to the injected parameter?如何将我的自定义数据格式从查询绑定到注入的参数?

You can use custom Model Binder to accomplish this.您可以使用自定义模型绑定器来完成此操作。 Here is a sample code:这是一个示例代码:

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) 
{
    ...
}

Am submitting this for ASP core 2.0 in the startup.cs add我在 startup.cs 添加中为 ASP 核心 2.0 提交这个

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

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


                // 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");


            });

this will make the model binding accept the format dd/MM/yyy这将使模型绑定接受格式 dd/MM/yyy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM