从c#

我有一个在C#后端上运行的API调用,但是Angular前端似乎将C#答复视为错误。请注意,对象的文本为“已添加注释”,表示已发回200 OK响应。为什么catchError函数会触发?

C#方法:

[HttpPost("AddComments")]
public actionResult<string> AddComment(BillingComments b)
{
    try
    {
        return StatusCode(200,"comment added");
    }
    catch (Exception e)
    {
        return StatusCode(500,"error adding comment");
    }
}

角度方法:

submitComment(newComment: BillingComments): any {
    return this.http.post('/api/BillingLg/AddComments',newComment)
        .pipe(catchError(this.appSvc.handleError<string>('submitComment','comment submitting err')));
}

appSvc.handleError返回的错误:

  

服务错误:submitComment失败   消息:http://localhost:49975/api/BillingLg/AddCommentsStatus解析期间的Http错误:200详细信息:{“错误”:{},“文本”:“添加了注释”}文本:确定并指定了返回类型(正常失败)

mattkk 回答:从c#

默认情况下,Angular解析API对对象的响应,因此默认情况下,它期望从API返回JSON字符串。

因此,您有两个选择,要么返回JSON而不是字符串(建议使用字符串),类似

return StatusCode(200,"{\"status\": \"comment added\"}");

或者您可以使HttpClient期望返回一个字符串:

this.http.post('/api/BillingLg/AddComments',newComment,{responseType: 'text'})
    .pipe(catchError(this.appSvc.handleError<string>('submitComment','comment submitting err')));
本文链接:https://www.f2er.com/3163915.html

大家都在问