Error: "the application completed without reading the entire request body" Angular/C#

Error: "the application completed without reading the entire request body" Angular/C#

我在 Angular 服务中发送 string 时出错。

我在使用 Postman 发送字符串时尝试 运行 我的存储过程,一切正常。

邮递员:

但是,当我通过我的服务发送字符串时,它不起作用。

user.service.ts:

addUser(user: string): Observable<any> {
  return this.http.post<string>('/api/user/AddUser', user)
    .pipe(catchError(this.handleError));
}

控制台错误:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost3 Request finished in 11.3875ms 400 application/json; charset=utf-8

info: Microsoft.AspNetCore.Server.Kestrel[32] Connection id "0HLL95U87FBQE", Request id "0HLL95U87FBQE:00000003": the application completed without reading the entire request body.

浏览器错误:

所以我真的不知道API到底得到了什么,因为它期望的结果必须是一串字符。

用户控制器 C#:

[HttpPost]
public User AddUser([FromBody]string user)
{
  return objUser.AddUser(user);
}

如果你能解决我的问题,我很感兴趣。 提前谢谢你。

编辑: 通过这样修改我的服务:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
})

addUser(user: string): Observable<any> {
    return this.http.post<User>('/api/user/AddUser', user.toString(), httpOptions)
      .pipe(catchError(this.handleError));
}

我收到这个新错误: 知道A是字符串中名字的第一个字母

确保将 http header 中的 content-type 设置为与您在 Postman 中设置的相同并实际发送 JSON。您还希望 post 到 return 用户 object 所以您的 userservice.ts 将是这样的:

addUser(user: string): Observable<any> {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json'
  })
  return this.http.post<user>('/api/user/AddUser', JSON.stringify(user), httpOptions)
    .pipe(catchError(this.handleError));
}

我没有看到任何影响此错误的代码,唯一想到的是字符串或 JSON 对象需要进行字符串化,这与 Postman 不同。所以最好在将请求正文传递给 API.

之前始终对其进行字符串化

试试这个:

addUser(user: string): Observable<any> {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json'
  })

  var userName = JSON.stringify(user);  // This

  return this.http.post<user>('/api/user/AddUser', userName, httpOptions)
    .pipe(catchError(this.handleError));
}