【问题标题】:HttpGet IActionResult method calling microservice returns all attributes as nullHttpGet IActionResult 方法调用微服务返回所有属性为空
【发布时间】:2022-01-24 10:02:33
【问题描述】:

我正在关注this tutorial,并专门使用基本用法部分中的代码。

当我从 Postman 向 http://localhost:9000/api/gateway 发送 GET 请求时,我得到了正确数量的对象,与数据库中的一样多,但所有属性都为空。

我尝试将 ReadAsStreamAsync 更改为 ReadAsStringAsync,实际上我得到了一个大字符串,即数据库中所有记录的数组。

那里的属性不是空的,但我不知道如何将字符串解析为 IEnumerable 对象,所以这对我没有多大帮助。

有人知道我可能缺少什么吗?请参阅下面的控制器方法。

请注意,该方法向 localhost:5000 发送 HTTP 请求,但该方法本身在 localhost:9000 上接收传入请求。

目标是创建一个 API 网关,它调用另一个微服务,并且不应该直接访问它正在调用的微服务的数据库。

public async Task<IActionResult> GetAllPatientsAsync()
    {
        var httpRequestMessage = new HttpRequestMessage(
HttpMethod.Get, "http://localhost:5000/api/patients")
        {
            Headers =
        {
            { HeaderNames.Accept, "application/json" }
        }
        };
        var httpClient = httpClientFactory.CreateClient();
        var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);

        if (httpResponseMessage.IsSuccessStatusCode)
        {
            using var contentStream =
                await httpResponseMessage.Content.ReadAsStreamAsync();
            PatientDtos = await JsonSerializer.DeserializeAsync
                <IEnumerable<PatientDto>>(contentStream);                

        }


        if (PatientDtos == null) return NotFound(); // 404 Not Found

        return Ok(PatientDtos);
    }

【问题讨论】:

    标签: microservices httpclient api-gateway jsonserializer


    【解决方案1】:

    原来这是 JsonSerializer 的问题。以下更改对我有用:

    PatientDtos = await JsonSerializer.DeserializeAsync<IEnumerable<PatientDto>>(
     contentStream, new JsonSerializerOptions
     {
       PropertyNamingPolicy = JsonNamingPolicy.CamelCase
     });
    

    更多信息here

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多