HttpClient returns 具有默认值的数据 (Blazor)

HttpClient returns data with default values (Blazor)

我有 Blazor WASM 应用程序 (dotnet 6)。我无法从 api 控制器获取数据。调用命中控制器方法。 HttpClient 收到响应,状态为OK,但返回数据有默认值。你能告诉我我做错了什么吗?

我做错了什么? 谢谢

// Controller:
[ApiController]
[Route("test")]
public class TestController : ControllerBase
{
    [HttpGet]
    [Route("data")]
    [ProducesResponseType(typeof(TestStruc), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetTest()
    {
        var data = new TestStruc();
        data.Id = 7;
        data.IsUse = true;
        data.Path = "root/bin/item";

        await Task.Delay(10); // instead of async query on db

        return HttpApiRep.Ok(data);
    }
}
// Blazor:
var res = await Http.GetAsync("test/data");
// res.StatusCode - Status code is OK
var data = await res.Content.ReadFromJsonAsync<TestStruc>();
// data have default values
// Data structure
public class TestStruc
{
    public int Id { get; set; } = 0;
    public bool IsUse { get; set; } = false;
    public string Path { get; set; } = "";
}

更新:

如果我调用 await res.Content.ReadAsStringAsync(),我将得到:

{"data":{"id":7,"isUse":true,"path":"root/bin/item"},"status":"ok","errorCode":"undefined","errorMessage":"","isOk":true}

但是当我调用 await res.Content.ReadFromJsonAsync<TestStruc> () 时,我得到一个具有默认值的对象。

反序列化可能有问题?

什么是HttpApiRep?我认为它包裹了你的 return.

这应该有效:

//return HttpApiRep.Ok(data);
  return Ok(data);

或者,确保 HttpApiRep 或仿真器在客户端中可用并使用

var response = await res.Content.ReadFromJsonAsync<HttpApiRep>();
var data = response.data;