Controlling Datetime Parameter Formatting in Webapi 2

How to send datetime from mvc to web api as a parameter?

When sending dates to an API, it is recommended to use a format that is independent of the culture. Widely used is the ISO 8601 format.

You can convert your dates to ISO 8601 by calling ToString("O"):

var postTask = client.GetAsync("/api/Values/Applications?fromDate=" + FromDate. ToString("O") + "&toDate=" + ToDate.ToString("O"));

For details on the Format, see this link:
https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#the-round-trip-o-o-format-specifier

Please also note that the timezone is another parameter to respect, so transmitting and also expecting the dates as UTC is a good practice to avoid timezone related issues.

How to filter data by datetime format parameter in ASP.NET WEB API

Your mapping started by the datetime endpoint is trying to map an IEnumerable<ToDoListDto> while your integer endpoint is mapping a single ToDoListDto.

If you want to map each item in the collection individually (which is what the integer ID endpoint is doing), change the mapping in the datetime endpoint to the following:

return Ok(todo.Select(item => _mapper.Map<ToDoListDto>(item));

or, if you want to map the entire collection you have to be explicit and specify the type as IEnumerable<ToDoListDto>:

return Ok(_mapper.Map<IEnumerable<ToDoListDto>>(todo));

Asp.net web API datetime format

If you are posting this via JSON then you should be able to create a JSON.NET converter for your date format.

In fact in researching this answer I found this full example on SO WebApi Json.NET custom date handling

Obviously just alter the conversion in MyDateTimeConvertor to be something that uses the current culture and the format you spefified.

DateTime.ParseExact(reader.Value.ToString(), "dd/mm/yyyy", CultureInfo.CurrentCulture);

AND

writer.WriteValue(((DateTime)value).ToString("dd/mm/yyyy"));

How to POST a DateTime value to a Web API 2 controller

You can't post non-objects directly, you need to wrap them in side an object container when using FromBody.

[RoutePrefix("api/Example")]
public class ExampleController : ApiController
{
[Route("Foo")]
[HttpGet]
public string Foo([FromUri] string startDate)
{
return "This is working";
}

[Route("Bar")]
[HttpPost]
public string Bar([FromBody] BarData data)
{
return "This is not working";
}
}

public class BarData{
public DateTime startDate {get;set;}
}

The other way it could work is if you form-encode the value like this using the = symbol (note you are sending it as a non-object, the curly braces have been removed).

"=2016-01-01T00:00:00.0000000-00:00"


Related Topics



Leave a reply



Submit