我有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 HttpApiRep.Ok(data);
return Ok(data);
或者,确保客户端中有HttpApiRep
或模拟物,并使用
var response = await res.Content.ReadFromJsonAsync<HttpApiRep>();
var data = response.data;