0

I implemented a custom web api model binder for a parameter of type DateTime? .

I am passing the string "2022-02-03T12:41:00.9406071+02:00" and inside the BindModel function, bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue is "2022-02-03T12:41:00.9406071 02:00" (replacing the '+' character with empty space)

Using debugger, I can see the full URL inside the actionContext.Request, and the '+' is there.

Weirdly enough, if I pass "2022-02-03T12:41:00.9406071-02:00", the '-' doesn't get replaced.

Because of this, I can't manage to parse the string to a DateTime.

My custom ModelBinder class :

public class CustomApiParameterBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var dateString = value != null ? value.AttemptedValue : "";
        bindingContext.Model = ParseDateTime(dateString);
        return true;
    }
    public List<string> DateTimeFormats = new List<string> { "yyyy-MM-ddTHH:mm:ss.fffffffK", "yyyy-MM-ddTHH:mm:ss.fffffff K", "yyyy-MM-ddTHH:mm:ss", "MM/dd/yyyy HH:mm" };
    public DateTime? ParseDateTime(string dateToParse)
    {
        var enUs = new CultureInfo("en-US");

        foreach (var format in DateTimeFormats)
        {
            DateTime validDate;

            if (DateTime.TryParseExact(
                s: dateToParse,
                format: format,
                provider: enUs,
                style: DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces,
                result: out validDate))
            {
                return validDate;
            }
        }

        return null;
    }
}

I registered my model binder like so, inside the WebApiConfig.Register(HttpConfiguration config) function :

config.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(typeof(DateTime?), new CustomApiParameterBinder()));

Why is this '+' replacement happening, and as a back-up solution, how can I parse the spaced string into a DateTime? (without splitting, because I have to account for other dateTime formats that have space in them)

Silviu.
  • 486
  • 1
  • 4
  • 13

0 Answers0