Home > Mobile >  ASP.NET POST request with DateTime as parameter issue
ASP.NET POST request with DateTime as parameter issue

Time:11-09

I'm trying to pass from my client-side (angular) a date object to my API. (POST request)

Unforently, The API receives it but the date is absolutely wrong.

Sending: Thu Nov 11 2021 10:00:00 GMT 0200

Reviced: 1/1/0001 12:00:00 AM

The controller:

    [HttpPost("{appointment}")]
    public async Task<ActionResult> SetAppointment(DateTime setAppointment)
    {
        // code
    }

Client-side

setAppointment(date) {
return this.http.post(environment.apiUrl   'barber/appointment', date);}

When date - is a DateTime object.

I have tried sending it as a string and then parsing it to a DateTime object and it kind of works but this is not my desired result.

I have tried explicitly parsing the date to a DateTime object on the client-side before sending, but it didn't work as well.

The expected result is to get the date as DateObject straight away in the controller.

Any ideas of why this type of thing happens? I understand that js and c# treat DateTime object in a different way but don't really understand how can I fix it or work around it without sending it as a string.

Thank you !!!

CodePudding user response:

Use moment library in Angular in order to send the wanted value in a format that will be automatically cast into DateTime format variable.

CodePudding user response:

Issue one: Parameter Naming

The annotation [HttpPost("{appointment}")] contains a variable appointment which isn't captured by the method SetAppointment because none of the parameters have this name. Instead you have a parameter named setAppointment. The names will have to match.

Issue two: URI

No sample URI is provided in the problem, ensure that it is encoded correctly as that is a common pitfall.

Issue three: Format of Date

Typically a server might have multiple different types of clients using it. Typically the client conforms to the server's date format (use a standard date format though). You can choose to have the server follow the format you are passing from Angular so long as it's encoded. In that case you could instead retrieve appointment as a string and parse it using a custom date and time format that matches what the server will receive.

  • Related