ReadFromJsonAsync 返回具有 Null 值的对象属性

har*_*ris 1 webassembly asp.net-core blazor

我有一个 Blazor WebAssembly 应用程序(ASP.Net Core 托管,渐进式 Web 应用程序),其逻辑如下:

客户:

 protected override async Task OnInitializedAsync()
    {
        string token = await _loginService.GetToken();

        _http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        
        var result = await _http.PostAsJsonAsync("api/api/getcalllogs", userCallsRequestFilters);

        if (result.IsSuccessStatusCode)
        {
            var morUserCallLogs = await result.Content.ReadFromJsonAsync<MorUserCallLogsResponse>();

            await js.InvokeAsync<object>("TestDataTablesAdd", "#example");
        }
        else
        {
            morUserCallLogs = new MorUserCallLogsResponse();
        }
    }
Run Code Online (Sandbox Code Playgroud)

服务器:(服务器端 API 我有以下代码按预期工作:)

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class MorApiController : ControllerBase
...

[HttpPost("getcalllogs")]
public async Task<MorUserCallLogsResponse> GetCallLogs ([FromBody] MorUserCallsRequestFilters filters)
{
...
return result;
Run Code Online (Sandbox Code Playgroud)

服务器端控制器 API 填充模型正常,当我检查时,我看到以下快照(* 为了安全起见,某些值已被清除) 在此处输入图片说明

模型:(我的 MorUserCallLogsResponse 模型如下所示:)

namespace MyNumberV2.Model
{
    public class MorUserCallLogsResponse
    {
        public MorUserCallLogsResponse()
        { 
            Calls = new List<MorCall>();
        }
        public string Error { get; set; }
        public bool IsSuccessfull { get; set; }
        public string userid;
        public string username;
        ...
        ...
        public List<MorCall> Calls { get; set; }
        public class MorCall
        {
            public string calldate2;
            public string timezone;
            ...
            ...
        }
    }
Run Code Online (Sandbox Code Playgroud)

回到 blazor,当我尝试在以下行读取此返回的对象时:

var morUserCallLogs = await result.Content.ReadFromJsonAsync<MorUserCallLogsResponse>();
Run Code Online (Sandbox Code Playgroud)

我检索到的模型如下所示: 在此处输入图片说明

正如您所看到的,我检索到的模型包含具有 140 个嵌套调用对象模型的所有属性,但是所有属性都是 NULL...

e03*_*050 7

我必须使用以下属性注释 using System.Text.Json.Serialization

 [JsonPropertyName("access_token")]
 public string AccessToken { get; set; }
Run Code Online (Sandbox Code Playgroud)


har*_*ris 5

我忘了加get;放; 对于我所有的模型属性...

{ 得到; 放; }

  public string Error { get; set; }
  public bool IsSuccessfull { get; set; }
  public string userid { get; set; }
  public string username { get; set; }
  .....
Run Code Online (Sandbox Code Playgroud)

  • 好的,字段不会序列化,属性会序列化。 (2认同)
  • 此外,设置者必须是公开的。我仍然使用 Newtonsoft 的原因之一 (2认同)