在网关服务中反序列化 JSON 微服务时出错

时间:2021-05-02 06:38:01

标签: c# json asp.net-web-api microservices api-gateway

我有一个网关服务和一个微服务客户

网关服务调用来自客户微服务的方法。

客户服务入口点如下所示:

[HttpGet("GetAll", Name = nameof(GetAll))]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<List<CustomerListVm>>> GetAll()
{
    var dtos = await _mediator.Send(new GetCustomersListQuery());

    return Ok(dtos);
}

当我从 swagger 调用这个方法时,结果没问题,没问题

现在我从网关服务调用相同的入口点

[HttpGet("GetAll", Name = nameof(GetAll))]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<List<CustomerDto>> GetAll()
{
    var dtos = this.customerService.GetAll();

    return Ok(dtos);
}


public async Task<List<CustomerDto>> GetAll()
{
    var response = await this.httpClient.GetAsync("url customer service Getall entry point");

    var result = await response.ReadContentAs<List<CustomerDto>>();

    return result;
}

一种扩展方法,用于将客户服务 json 结果中的答案转换为网关服务端的对象。

public static async Task<T> ReadContentAs<T>(this HttpResponseMessage response)
{
    if(!response.IsSuccessStatusCode)
        throw new ApplicationException($"Something went wrong calling the API: {response.ReasonPhrase}");

    var dataAsString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

    var obj = JsonSerializer.Deserialize<T>(
        dataAsString,
        new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

    return obj;
}

dataAsString 包含来自客户服务的正确结果。

[{"customerId":
        "b0788d2f-8003-43c1-92a4-edc76a7c5dde",
        "reference":"2020001",
        "lastName":"MyLastName",
        "firstName":null,
        "email":null
}]

我想把 JSON 结果放在这个对象中

public class CustomerDto
{
    public Guid CustomerId { get; set; }

    public string Reference { get; set; }

    public string LastName { get; set; }

    public string FirstName { get; set; }

    public string Email { get; set; }
}

在startup.cs的网关服务中,我有这个:

services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

但是我得到了一个错误导致招摇:

{
  "stateMachine": {
    "<>1__state": 0,
    "<>t__builder": {},
    "<>4__this": {}
  },
  "context": {},
  "moveNextAction": {
    "method": {
      "name": "MoveNext",
      "declaringType": "System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[[System.Collections.Generic.List`1[[Gateway.Web.Models.CustomerDto, Gateway.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[Gateway.Web.Services.CustomerService+<GetAll>d__2, Gateway.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
      "reflectedType": "System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[[System.Collections.Generic.List`1[[Gateway.Web.Models.CustomerDto, Gateway.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[Gateway.Web.Services.CustomerService+<GetAll>d__2, Gateway.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",

1 个答案:

答案 0 :(得分:0)

在这段代码中:

[HttpGet("GetAll", Name = nameof(GetAll))]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<List<CustomerDto>> GetAll()
{
    var dtos = this.customerService.GetAll();

    return Ok(dtos);
}

应该是:

[HttpGet("GetAll", Name = nameof(GetAll))]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<List<CustomerDto>>> GetAll()
{
    var dtos = await this.customerService.GetAll();

    return Ok(dtos);
}

您没有await处理它 -- 这就是它返回序列化任务的原因。

相关问题