【问题标题】:ModelBinder and Dates in ASP.NET Core 2ASP.NET Core 2 中的 ModelBinder 和日期
【发布时间】:2017-11-21 13:59:09
【问题描述】:

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

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

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

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

  • 2017 年 12 月 31 日 这样的日期可以。
  • 而像 31-12-2017 这样的日期是行不通的。

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

【问题讨论】:

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


【解决方案1】:

您可以使用自定义模型绑定器来完成此操作。这是一个示例代码:

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

【讨论】:

    【解决方案2】:

    我在 startup.cs 添加中为 ASP core 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");
    
    
                });
    

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

    【讨论】:

    • 不知道为什么 opts.DefaultRequestCulture 有两次 :)
    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 2019-04-14
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2017-09-21
    • 1970-01-01
    相关资源
    最近更新 更多