Reputation: 13972
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.
How can I make it bind my custom data format from the query to the injected parameter?
Upvotes: 4
Views: 4386
Reputation: 1779
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
Upvotes: 1
Reputation: 31282
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)
{
...
}
Upvotes: 2