Yuri Makassiouk
Yuri Makassiouk

Reputation: 557

DateTime values binding in ASP.NET WebAPI (4.x Framework)

I can't seem to understand what governs how DateTime values are parsed when WebAPI's binding framework operates. Some test code:

public class TestSearchModel
{
    public DateTime? From { get; set; }
    public DateTime? Until { get; set; }
    public string Freetext { get; set; }
}

...

    public HttpResponseMessage Get([FromUri] TestSearchModel searchModel)
    {
        //CultureInfo culture = Thread.CurrentThread.CurrentCulture;

        return Request.CreateResponse(
            $"Received search request with Freetext: {searchModel.Freetext}, From: {searchModel.From}, Until: {searchModel.Until}");
    }

And then I test with various requests like:

http://localhost:9000/api/search?freetext=oi-vei!&from=14.07.2020 (1)

http://localhost:9000/api/search?freetext=oi-vei!&from=07.14.2020 (2)

http://localhost:9000/api/search?freetext=oi-vei!&from=2020-07-14 (3)

Freetext is only there as a test - it always binds just fine. Dates in format like (3) bind fine, I guess that is close enough to culture-invariant format. What I do not get is why the format (1) would not work when the application's culture is set to something with this date format (Norwegian in my case).

Our intention is to have consumers of the API use culture-invariant formats in any case, but we also thought it would be nice to be able to recognize national formats - when we anyway set the current culture from the requests' headers. I realize I can hook up my own binder and program whatever I want, but this seems like something that the framework should already have. It does parse the datetime values one way or another. So the question is: how does the binding system decides what date format to use when attempting parsing a date value?

Upvotes: 0

Views: 38

Answers (1)

Inam Abbas
Inam Abbas

Reputation: 486

I,m not sure but I hope this code helps you more. You can change your date format and also pass case sensitive parameters in quertString.

http://localhost:9000/api/search?Freetext=oi-veii&From=14-07-2020

Upvotes: 1

Related Questions