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

时间:2020-08-26 07:57:32

标签: asp.net-core blazor webassembly

我有一个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();
        }
    }

服务器:(服务器端API,我有以下代码可以正常使用:)

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

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

服务器端控制器API会很好地填充模型,当我检查时会看到以下快照(*为了安全起见,某些值已被清空) enter image description here

模型:(我的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;
            ...
            ...
        }
    }

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

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

我检索的模型如下: enter image description here

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

3 个答案:

答案 0 :(得分:2)

我忘记添加get;组;对于我所有的模型属性...

{得到;组; }

  public string Error { get; set; }
  public bool IsSuccessfull { get; set; }
  public string userid { get; set; }
  public string username { get; set; }
  .....

答案 1 :(得分:1)

"api/api/getcalllogs"[Route("api/[controller]")][HttpPost("getcalllogs")]

不匹配

在我阅读时,网址应该为"api/MorApi/getcalllogs"

但是再说一次,应该会产生404或400

答案 2 :(得分:0)

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

 [JsonPropertyName("access_token")]
 public string AccessToken { get; set; }