.NET Core 5 Web 应用程序中具有复杂 json 值的 Http GET 请求

Http GET requests with complex json value in .NET Core 5 web app

我正在尝试执行获取请求,这是我的剃须刀页面 class:

public class IndexModel : PageModel
{
    public IEnumerable<ApiAnime> ApiData { get; set; } 

    public async Task<IActionResult> OnGet()
    {
        var request = new HttpRequestMessage(HttpMethod.Get,
            "https://api.aniapi.com/v1/anime");
        var client = _clientFactory.CreateClient();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        var response = await client.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            ApiData = await JsonSerializer.DeserializeAsync<IEnumerable<ApiAnime>>(responseStream);
        }

        else
        {
            ApiData = new List<ApiAnime>();
        }

        return Page();
    }
}

这个剃须刀页面 class 似乎可以使用更简单或更直接的 json 值。但是这个 api "https://api.aniapi.com/v1/anime" 似乎不起作用。 现在这是我的 json class:

public class ApiAnime
{

    public class Rootobject
    {
        public int status_code { get; set; }
        public string message { get; set; }
        public Data data { get; set; }
        public string version { get; set; }
    }

    public class Data
    {
        public int current_page { get; set; }
        public int count { get; set; }
        public Document[] documents { get; set; }
        public int last_page { get; set; }
    }

    public class Document
    {
        public int anilist_id { get; set; }
        public int mal_id { get; set; }
        public int format { get; set; }
        public int status { get; set; }
        public Titles titles { get; set; }
        public Descriptions descriptions { get; set; }
        public DateTime start_date { get; set; }
        public DateTime end_date { get; set; }
        public int season_period { get; set; }
        public int season_year { get; set; }
        public int episodes_count { get; set; }
        public int episode_duration { get; set; }
        public string trailer_url { get; set; }
        public string cover_image { get; set; }
        public string cover_color { get; set; }
        public string banner_image { get; set; }
        public string[] genres { get; set; }
        public int score { get; set; }
        public int id { get; set; }
        public int prequel { get; set; }
        public int sequel { get; set; }
    }
}

我得到的错误是

The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[AnimDbNet.ApiModel.ApiAnime].
ApiData = await JsonSerializer.DeserializeAsync<IEnumerable<ApiAnime>>(responseStream);

我正在使用 .NET Core 5。 有谁知道如何解决这个错误?

您不需要 IEnumerable,这应该可以通过使用 Rootobject 来实现。

JsonSerializer.DeserializeAsync<Rootobject>(responseStream);

此 API 发送的 json 以 :

开头
{
"status_code": 200,
"message": "Page 1 contains 100 anime. Last page number is 153 for a total of 15280 anime",
"data": {
...

这是你的根对象的开始。

错误是由于试图解析 API 的 return 值,它不是 JSON 数组而是 JSON 对象,而不是 IEnumerable。

 ApiData = await JsonSerializer.DeserializeAsync<IEnumerable<ApiAnime>>(responseStream);

解决方案是直接解析为 ApiAnime.Rootobject,然后使用 apiData.Data 访问您主页上的数据。 您的代码将如下所示。

public class IndexModel : PageModel
{
    public ApiAnime.Rootobject ApiData { get; set; } 

public async Task<IActionResult> OnGet()
{
    var request = new HttpRequestMessage(HttpMethod.Get,
        "https://api.aniapi.com/v1/anime");
    var client = _clientFactory.CreateClient();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.SendAsync(request);

    if (response.IsSuccessStatusCode)
    {
        var responseStream = await response.Content.ReadAsStreamAsync();

        ApiData = await JsonSerializer.DeserializeAsync<ApiAnime.Rootobject>(responseStream);
    }

    else
    {
        ApiData = new ApiAnime.Rootobject();
    }

    return Page();
 }
}

您不需要 IEnumerable。试试这段代码。它在 Visual Studio 中进行了测试并且可以正常工作。

public class IndexModel : PageModel
{
    public ApiData ApiData { get; set; } 

   
  public async Task<IActionResult> OnGet()
  {

  var apiDataRoot= await GetApiData(_httpClientFactory);

  if (apidatRoot.status_code=200)  ApiData=apiDataRoot.ApiData;
  else ... return error;
  
    return Page();
  }
}

获取ApiData

public async Task<ApiDataRoot> GetApiData(IHttpClientFactory httpClientFactory)
{
    var request = new HttpRequestMessage(HttpMethod.Get,
        "https://api.aniapi.com/v1/anime");
     var client = httpClientFactory.CreateClient();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.SendAsync(request);

    ApiDataRoot apiDataRoot = null;

    if (response.IsSuccessStatusCode)
    {
        var responseString = await response.Content.ReadAsStringAsync();

        apiDataRoot = System.Text.Json.JsonSerializer.Deserialize<ApiDataRoot>(responseString);
    }

    else
    {
        apiDataRoot = new ApiDataRoot {status_code=400, message="error"};
    }
    return apiDataRoot;
}

public class ApiData
{
    public int current_page { get; set; }
    public int count { get; set; }
    public List<Document> documents { get; set; }
    public int last_page { get; set; }
}
public class ApiDataRoot
{
    public int status_code { get; set; }
    public string message { get; set; }
    public ApiData data { get; set; }
    public string version { get; set; }
}
public class Titles
{
    public string en { get; set; }
    public string jp { get; set; }
    public string it { get; set; }
}


public class Descriptions
{
    public string en { get; set; }
    public string it { get; set; }
}

public class Document
{
    public int anilist_id { get; set; }
    public int mal_id { get; set; }
    public int format { get; set; }
    public int status { get; set; }
    public Titles titles { get; set; }
    public Descriptions descriptions { get; set; }
    public DateTime start_date { get; set; }
    public DateTime end_date { get; set; }
    public int season_period { get; set; }
    public int season_year { get; set; }
    public int episodes_count { get; set; }
    public int episode_duration { get; set; }
    public string trailer_url { get; set; }
    public string cover_image { get; set; }
    public string cover_color { get; set; }
    public string banner_image { get; set; }
    public List<string> genres { get; set; }
    public int score { get; set; }
    public int id { get; set; }
    public int? prequel { get; set; }
    public int? sequel { get; set; }
}