简体   繁体   中英

ModelBinder and Dates in ASP.NET Core 2

All the dates in my URLs come in this format: dd-MM-yyyy . Example: 31-12-2017

Currently, my Web API has a method like this

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

The problem is that my Web API seems work ONLY with dates formatted in US English .

  • A date like 12-31-2017 will work.
  • Whereas a date like 31-12-2017 won't work.

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

            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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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