Search code examples
angularasp.net-web-apiasp.net-coreangular-httpclient

Angular 7 HttpClient put request params sending null values to endpoint


I have an Angular service with this Put request method:

put(peopleFieldID: number, peopleFieldName: string): Observable<number> {
let params = new HttpParams();
params = params.append("peopleFieldID", peopleFieldID.toString());
params = params.append("peopleFieldName", peopleFieldName);

return this.http
  .put<number>(this.url, { params: params })
  .pipe(catchError(this._errorHandling.handleError.bind(this)));}

The above hits this endpoint on my .net core API:

    [Authorize(Roles = "Client")]
    [Route("")]
    [HttpPut]
    public IActionResult C_Update(int peopleFieldID, string peopleFieldName )
    {
        //Make call to the proper repo method.
        return Json(_peopleFieldRepo.C_Update(peopleFieldID, peopleFieldName));
    }

The two params, peopleFieldID and peopleFieldName, are always 0 and null. I have pinpointed that the Angular frontend sends the params correctly, but the backend cannot recognize them. I have many other endpoints where this works just fine.


Solution

  • You need to set query params using HttpParams and pass null for payload if you do not have any:

    const params = new HttpParams()
                .set('peopleFieldID', peopleFieldID.toString())
                .set('peopleFieldName', peopleFieldName);
    // if you have a payload to pass you can do that in place of null below
    return this.http
      .put<number>(this.url, null, { params: params })
      .pipe(catchError(this._errorHandling.handleError.bind(this)));}