【问题标题】:Response is null for Http Post call to web api - Angular 4对 Web api 的 Http Post 调用的响应为空 - Angular 4
【发布时间】:2018-07-29 20:01:22
【问题描述】:

我正在尝试使用 HttpClient 从 Angular 4 对 web api 进行后期调用。

这是我的后调用服务:

public add<T>(type:string, item: T): Observable<any> {
        console.log("api data : " + this.url + type);
        return this.http
            .post(this.url + type, JSON.stringify(item)).map((res: Response) => { console.log("rese: "+res); res});
    }

这是订阅上述服务的代码:

addArticleType(articleType: ArticleType): void {
        console.log("Service data : " + articleType);
        this.service.add("ArticleType", articleType).subscribe((val: any) => this.response = val),
            (error: any) => { console.log("Error is: " + error) },
            () => { console.log("resp: " + this.response) };

    }

这是 API

 public HttpResponseMessage Add(A item)
    {
        int a = this.service.Add(item);
        log.Debug("value: " + a);
        if (a > 0)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent("Data saved successfully.", Encoding.UTF8, "application/json");
            return response;
        }

        return Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Failed to save data");

    }

在 Post 调用时,API 接收调用并执行将数据存储在数据库中的任务。但是 Angular 不会接收 API 作为 HttpResponseMessage 发送的任何响应。

正如您在服务中看到的,我正在尝试在控制台中打印响应。这总是打印空值。作为回应,我希望 API 发送的消息“数据已成功保存。”,但我得到的是空值。

我可能遗漏了一些非常基本的东西。我查看了很多文章和博客,但没有找到任何可以解决问题的方法。

更新:

根据提供的指南,我更新了我的代码,如下所示。

通话后

  public add<T>(type:string, item: T): Observable<T> {
    console.log("api data : " + this.url + type);
    return this.http
        .post<T>(this.url + type, item);
}

订阅

addArticleType(articleType: ArticleType): void {
        console.log("Service data : " + articleType);
        this.service.add<ArticleType>("ArticleType", articleType)
            .subscribe(
            (val: any) => {
                this.response = val;
                console.log("res sub: " + this.response);
            },
            (error: any) => { console.log("Error is: " + error) },
            () => { console.log("resp: " + this.response) });

    }

它仍然在控制台中将响应打印为 null。

【问题讨论】:

  • 1st) 你为什么要把身体串起来? 2nd)你永远不会映射响应
  • 为什么你认为HttpClient.post方法的响应类型是Response?请阅读 angular.io 中的 http 指南
  • 而且add方法里面的map应该有return。
  • @Jota.Toledo 我们不知道他使用的是 httpclient 而不是 http。并且地图不需要返回,但可能需要变为.map(res =&gt; res.json())
  • 您能在开发控制台的“网络”选项卡中看到到达的响应吗?

标签: angular asp.net-web-api rxjs


【解决方案1】:

如果您的服务器没有返回任何内容(状态 200 没有正文),您需要设置 responseType: 'text' 以处理该行为

...
public add<T>(type:string, item: any): Observable<any> {
  return this.http.post(this.url + type, item, { responseType: 'text' });
}
...

并且在控制器中简单地处理成功和错误调用

this.service.add("ArticleType", articleType).subscribe(
  () => // success handle,
  err => // error handle
)

如果您需要在响应正文中接收文本消息,您需要确保它在开发控制台中传递(如果网络响应为空,请检查此How to create a response message and add content string to it in ASP.NET 5 / MVC 6) 当浏览器收到响应时,您可以像这样处理它:

...
// Service
public add<T>(type:string, item: any): Observable<any> {
  return this.http.post(this.url + type, item);
}

...
// Controller
this.service.add("ArticleType", articleType).subscribe(
  res => {
    console.log(res);
    // here some success handle,
  }
  err => // error handle
)

【讨论】:

  • 在你的服务器中尝试return Request.CreateResponse(HttpStatusCode.OK, "Your message here");Add()方法
  • 你是对的。问题在于响应的类型。将 { responseType: 'text' } 添加到帖子中就可以了。非常感谢。
  • 我很乐意提供帮助)
【解决方案2】:

您在此服务器端代码中返回的似乎不是有效的 JSON:

  response.Content = new StringContent(
       "Data saved successfully.",
       Encoding.UTF8,
       "application/json");

你应该有一些看起来像:

  response.Content = new StringContent(
       "{\"Result\": \"Data saved successfully.\"}",
       Encoding.UTF8,
       "application/json");

【讨论】:

  • 字符串是有效的 JSON 令牌。客户端 API 是否可以处理我不知道的问题,如果他们记录他们期望 JSON object 比这可能是问题,但如果他们打算接受任何 JSON 令牌那么这是一个有效的服务器响应。
  • 用引号字符括起来的字符串是有效的 JSON 标记。我在回答中没有详细说明问题中的代码尝试返回 application/json 媒体类型响应。此媒体类型要求响应是有效的 JSON 对象或 JSON 对象数组。这在接受的答案中很明显,客户端代码已更改为“强制”接受 text 响应以正确处理字符串。
  • 好点。我认为StringContent 实际上是一个字符串,但似乎不是,application/json 似乎也同意。但是,我看不到媒体类型如何要求它是对象或数组。你有那个链接吗? RFC 8259 似乎表明所有 JSON 令牌都是有效的“JSON 文本”,正如它所称的那样。我错过了什么吗?
  • 我也没有看到 RFC 明确指出响应必须只包含它描述的两种“结构”类型。 JSON found at this site 原始规范中的第二段明确说明只有这两种类型才是有效的 JSON。我使用的大多数 HTTP 客户端似乎都做出了相同的假设。这肯定是问题描述的问题的根本原因。感谢您查找 RFC!这教会我避免假设它们必然包含我在它们所基于的规范中看到的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
相关资源
最近更新 更多