C# 从另一个API调用API操作,读取json响应并向其添加一些额外属性

C# 从另一个API调用API操作,读取json响应并向其添加一些额外属性,c#,asp.net-mvc,asp.net-web-api,asp.net-core-webapi,C#,Asp.net Mvc,Asp.net Web Api,Asp.net Core Webapi,我有一个.netcore web api(localApi),它调用另一个web api(remoteApi)。 remoteApi返回json,我的目标是向该json添加一个新属性,并将其作为json返回给调用localApi的调用方 到目前为止,我的代码如下: var httpResponse = await httpClient.PostAsync(remoteApi), httpContent); // If the re

我有一个.netcore web api(localApi),它调用另一个web api(remoteApi)。 remoteApi返回json,我的目标是向该json添加一个新属性,并将其作为json返回给调用localApi的调用方

到目前为止,我的代码如下:

                var httpResponse = await httpClient.PostAsync(remoteApi), httpContent);

                // If the response contains content we want to read it!
                if (httpResponse.Content != null)
                {
                    responseContent = await httpResponse.Content.ReadAsStringAsync();

                    responseContent = responseContent.Insert(2, " \"isCachedResponse\": false,");

                    var retVal = await Task.Run(() => JsonConvert.SerializeObject(responseContent));
                    return Ok(retVal);
                }
这种方法的问题是响应是字符串而不是json。 如下图所示:

"\"{ \"isCachedResponse\": true, \\\"remoteApiResponse\\\":{ \\\"applicationId\\\":\\\"10001000000300071\\\", \\\"reasons\\\":[ { \\\"reason\\\":\\\"Score Cut Policy\\\" } ], \\\"decisionText\\\":\\\"Duplicate request; check UI for more information\\\", \\\"decisionCode\\\":\\\"Undecisioned\\\", \\\"officialNameOnFile\\\":{ \\\"firstName\\\":\\\"\\\", \\\"middleName\\\":\\\"\\\", \\\"lastName\\\":\\\"\\\" } } }\""

我该如何解决这个问题呢?

您可以返回一个普通字符串
ContentResult
,因为您已经有了所需的JSON,而不是开始一些额外的任务,执行一些手动序列化并返回一个
OkObjectResult

if (httpResponse.Content != null)
{
    responseContent = await httpResponse.Content.ReadAsStringAsync();

    responseContent = responseContent.Insert(2, " \"isCachedResponse\": false,");

    return this.Content(responseContent, "application/json");
}

很好的解释和示例代码。我希望这对我这个位置的其他人也有帮助。非常感谢。