错误:“应用程序已完成而未读取整个请求正文”Angular / C#

问题描述 投票:2回答:2

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

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

邮递员:enter image description here enter image description here

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

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请求在11.3875ms完成400 application / json;字符集= utf-8的

info:Microsoft.AspNetCore.Server.Kestrel [32]连接ID“0HLL95U87FBQE”,请求ID“0HLL95U87FBQE:00000003”:应用程序已完成,但未读取整个请求正文。

浏览器错误:

enter image description here

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

UserController 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是字符串中第一个名字的第一个字母。

enter image description here

c# angular typescript angular-services angular-httpclient
2个回答
1
投票

我没有看到任何影响此错误的代码,唯一需要注意的是字符串或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));
}

3
投票

确保将http标头中的内容类型设置为与您在Postman中设置的相同,并实际发送JSON。你还希望帖子返回一个用户对象,这样你的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));
}
© www.soinside.com 2019 - 2024. All rights reserved.