Angular 7 HttpClient放置请求参数,向端点发送空值

时间:2019-03-28 02:04:41

标签: angular asp.net-web-api asp.net-core angular-httpclient

我有一个带有Put请求方法的Angular服务:

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)));}

上面的代码在我的.net核心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));
    }

这两个参数peopleFieldID和peopleFieldName始终为0,并且为null。我已经确定了Angular前端正确发送了参数,但是后端无法识别它们。我还有许多其他端点可以正常工作。

1 个答案:

答案 0 :(得分:3)

如果没有任何内容,则需要使用HttpParams设置查询参数,并为有效负载传递null

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)));}