4

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?

1

2 Answers 2

2

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) 
{
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Not sure why opts.DefaultRequestCulture is there twice :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.