【问题标题】:Make my own API capable of requesting from another API使我自己的 API 能够从另一个 API 请求
【发布时间】:2023-03-18 21:34:01
【问题描述】:

我有一个现有且正常运行的 API,它现在必须能够从另一个外部 API 获取数据。我怎样才能做到最好?

我尝试过使用 HTTPClient,但我似乎无法让它工作。我得到的错误:

“没有 MediaTypeFormatter 可用于从媒体类型为 'text/html' 的内容中读取类型为 'IList`1' 的对象。” -> 我在第 37 行收到此错误。你能发现它和/或告诉我如何以不同的方式做到这一点,考虑到我想要的只是数据(来自外部 API)而不是使用视图显示它,因为这是一个 API?

代码如下。我还创建了一个 Pastebin:https://pastebin.com/MuKjEVys

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;

namespace API.Controllers
{
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ExternalApiController : Controller
{
    private string ExternalApiLink = "https://blablabla.com/api";
    private string ExternalApiLinkGet = "/module/1/";
    [HttpGet("getdata")]
    public ActionResult<ExternalApi> GetDataFromExternal()
    {

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(ExternalApiLink);

            var requestApi = client.GetAsync(ExternalApiLinkGet);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "XXXX");
            requestApi.Wait();

            var resultFromApi = requestApi.Result;

            if (resultFromApi.IsSuccessStatusCode)
            {
                var readResponse = resultFromApi.Content.ReadAsAsync<IList<ExternalApi>>();
                readResponse.Wait();

                var data = readResponse.Result;

                return Json(data);
            }else
            {
                return NotFound();
            }
        }
    }
}

}

【问题讨论】:

  • 这表示您的 api 正在返回 html。不是 json 或 xml。所以显然它没有返回你所期望的。这就是为什么你不能把它当作一个列表来阅读。检查响应内容以找出原因。
  • 但这表明它是另一个外部 API,不是以 JSON 格式发送数据还是?
  • 是的,您可能会得到一个异常页面,或者您调用了错误的 url。搜索互联网以了解如何检查响应内容和状态代码。这应该可以告诉您为什么会发生这种情况。
  • 如果我尝试在 if 语句之前打印“resultFromApi”,我会收到 JSON 响应。在这里我可以看到它是正确的链接,我正在尝试从中获取数据和内容-类型是 text/html ...这可能是错误吗?我应该只请求一个说 application/json 的正文吗?
  • 您可以尝试在您的请求中发送Accept header(该答案中的第 3 行)。服务器不应返回带有 text/html 内容类型的 json...

标签: c# asp.net json api


【解决方案1】:

您的响应内容似乎是 json,而 content-type 是 text/html。如果是这种情况,首先要做的就是打电话给暴露服务的一方并让他们修复它。同时,您可以将响应的内容作为字符串读取,然后反序列化该字符串:

// Note that I made this method async.
public async Task<IActionResult> GetDataFromExternal()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(ExternalApiLink);

        // note that I moved this line above the GetAsync method.
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "XXXX");

        // note that I'm disposing the response
        using (var response = await client.GetAsync(ExternalApiLinkGet))
        {
            if (response.IsSuccessStatusCode)
            {
                // Since the response content is json, but the content-type
                // is text/html, simply read the content as a string.
                string content = await response.ReadAsStringAsync();

                // You can return the actual received content like below,
                // or you may deserialize the content before returning to make
                // sure it is correct, using JsonConvert.DeserializeObject<List<ExternalApi>>()
                // var data = JsonConvert.DeserializeObject<List<ExternalApi>>(content);
                // return Json(data);
                return Content(content, "application/json");
            }
            else
            {
                return NotFound();
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 2020-12-23
    • 2021-05-15
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    相关资源
    最近更新 更多