Search code examples
sqlangularasp.net-web-apihttp-status-code-400

HTTP 400 bad request Unexpected character encountered while parsing value Date


I'm having trouble posting a date from my angular application to my ASP.net web api. Ive logged the data to the console and I get the following error:

API Response error

In not entirely sure what is wrong with the date data I am trying to post. Is it in the wrong format? I'm using an Angular datetimepicker.

Model with the 'DateFound' field which I think is causing the problem:

export class Nclog {

id: number;
DateFound?:  Date;
LocationFound: string;
NCTypeId: number;
NCDescription: string;
ActionTaken: string;
CauseOfNc: string;
InvestigatedBy: string;
InvestigationStart?: Date;
InvestigationFinish?: Date;
CorrectiveAction: string;
AddressRootCause: string;
PreventsReoccurrance: string;
Valid: boolean;
ImplementedEffective: boolean;
FollowUpComments: string;
Effective: boolean;
EffectivenessComments: string;
Signed: string;
Date?: Date;
NCStatus: number;
NCNumber: number;
NotedBy: string;
DateTest: Date;
}

Service.ts

import { Injectable } from '@angular/core';
import { Nclog } from './nclog.model';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class NclogService {

  nclogFormData: Nclog;
  list: Nclog[];
  readonly rootURL = "https://localhost:44322/api"

  constructor(private http: HttpClient) { }

  postLog(nclogFormData: Nclog) {
    console.log(JSON.stringify(nclogFormData));
    nclogFormData.id = 0;
    return this.http.post(this.rootURL+'/NCLog', nclogFormData);
  }

  refreshList(){
    this.http.get(this.rootURL+'/NCLog')
    .toPromise().then(res => this.list = res as Nclog[]);
  }

HTML

<div class="form-group col-md-6">
      <label>Date NC Found</label>
      <input class="form-control" placeholder="yyyy-mm-dd"
       name="DateTest" #DateFound="ngModel" [(ngModel)]="service.nclogFormData.DateFound" ngbDatepicker #d="ngbDatepicker">
      <div class="input-group-append">
      <button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>
</div>

Solution

  • Ok so the answer to this was that the datepicker format was wrong for the API.

    So i used moment.js to format the date field before posting it.

     postLog(nclogFormData: Nclog) {
        console.log(JSON.stringify(nclogFormData));
        nclogFormData.id = 0;
        nclogFormData.DateFound = moment().format();
        return this.http.post(this.rootURL+'/NCLog', nclogFormData);
    
      }