【问题标题】:Angular 7 HttpClient put request params sending null values to endpointAngular 7 HttpClient 将请求参数发送到端点
【发布时间】:2019-08-18 17:22:41
【问题描述】:

我有一个带有这个 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 前端正确发送参数,但后端无法识别它们。我还有许多其他端点都可以正常工作。

【问题讨论】:

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


    【解决方案1】:

    如果没有,您需要使用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)));}
    

    【讨论】:

    • 这确实解决了问题。我认为因为 body 参数是可选的,所以如果我不包含它也没关系。我没有将它包含在 Get 请求中,但我在 Post/Puts 中需要它是有道理的。谢谢!
    • 是的,Get 不需要正文,但 Put 和 POST 需要它,所以如果您没有任何需要,请发送 null。
    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2019-09-15
    • 2017-11-23
    • 2021-07-27
    相关资源
    最近更新 更多