【问题标题】:Calling an API action from another API, reading the json response and adding some extra properties to it从另一个 API 调用 API 操作,读取 json 响应并向其添加一些额外的属性
【发布时间】:2017-05-24 05:32:51
【问题描述】:

我有一个调用另一个 web api(remoteApi) 的 .netcore web api(localApi)。 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\\\":\\\"\\\" } } }\""

我怎样才能解决这个问题?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api asp.net-core-webapi


    【解决方案1】:

    您可以只返回一个纯字符串 ContentResult,因为您已经拥有所需的 JSON,而不是启动一些额外的任务、进行一些手动序列化并返回一个 OkObjectResult

    if (httpResponse.Content != null)
    {
        responseContent = await httpResponse.Content.ReadAsStringAsync();
    
        responseContent = responseContent.Insert(2, " \"isCachedResponse\": false,");
    
        return this.Content(responseContent, "application/json");
    }
    

    【讨论】:

    • 很好的解释以及示例代码。我希望这对我所在位置的其他人也有帮助。谢谢...
    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2021-11-20
    • 2020-02-10
    相关资源
    最近更新 更多