I have the Blazor WASM application (dotnet 6). I can't get the data from the api controller. The call hits the controller method. HttpClient receives a response, the status is OK, but the returned data has default values. Can you please advise me what I'm doing wrong?
What am I doing wrong? Thank you
// 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; } = "";
}
Update:
If I call await res.Content.ReadAsStringAsync()
, I'll get:
{"data":{"id":7,"isUse":true,"path":"root/bin/item"},"status":"ok","errorCode":"undefined","errorMessage":"","isOk":true}
But when I call await res.Content.ReadFromJsonAsync<TestStruc> ()
, I get an object with default values.
Maybe a problem with deserialization?
CodePudding user response:
Try this:
var _testStruc = await Http.GetFromJsonAsync<TestStruc>("test/data");
CodePudding user response:
What is HttpApiRep
? I think it wraps your return.
This should work:
//return HttpApiRep.Ok(data);
return Ok(data);