从.NET Core调用Rest API

问题描述 投票:-1回答:2

[我一直在.Net Core中进行一些API构建,并学习新功能。

我不知道如何调用以下内容

[HttpGet(Name = "GetBooks")] 
public async Task<ActionResult<IEnumerable<BookDisplay>>> Get([FromQuery]  BookSearch bookSearch)
    {

        var books = await _bookManager.Search(bookSearch);

        var paginationMetadata = new
        {
            totalCount = books.TotalCount,
            pageSize = books.PageSize,
            currentPage = books.CurrentPage,
            totalPages = books.TotalPages
        };
        Response.Headers.Add("X-Pagination", JsonSerializer.Serialize(paginationMetadata));
        var links = CreateGetLinks(bookSearch, books.HasNext, books.HasPrevious);
        var booksToReturn = new  
        {
            Value = books,
            links
        };

        return Ok(booksToReturn);             
    }

我可以大张旗鼓地称呼它并获得关注

请求URL

https://localhost:5001/api/Books?Author=IanFleming&Style=Spy

服务器响应

{
  "value": [
    {
      "id": 1,
      "Author": "Ian Fleming",
      "Stye": "Spy",
      "Title": "Dr No"
    },
    {
      "id": 1,
      "Author": "Ian Fleming",
      "Stye": "Spy",
      "Title": "Casino Royale"
    }
  ],
  "links": [
    {
      "href": "https://localhost:5001/api/Books/Author=Ian%20Fleming&Style=Spy&PageNumber=1&PageSize=10",
      "rel": "self",
      "method": "GET"
    }
  ]
}



    Response headers
     content-type: application/json; charset=utf-8 
     date: Tue, 26 May 2020 12:18:04 GMT 
     server: Kestrel 
     x-pagination: {"totalCount":2,"pageSize":10,"currentPage":1,"totalPages":1}

当测试并大摇大摆时,一切正常。但是我一直在构建一个.Net Core应用程序,该应用程序使用以下代码来调用它,

   public async Task<IEnumerable<BookDisplay>> BookSearch(BookSearch search)
    {
        try
        {
            var searchJson =
            new StringContent(JsonSerializer.Serialize(search), Encoding.UTF8, "application/json");


            return await JsonSerializer.DeserializeAsync<IEnumerable<BookDisplay>>
                        (await _httpClient.GetStreamAsync($"/api/Books?Author=IanFleming&Style=Spy"), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

我收到以下错误[JSON值无法转换为System.Collections.Generic.IEnumerable`1 [DTO.BookDisplay]。路径:$ |行号:0 | BytePositionInLine:1。

我知道我通过对参数中的硬编码跳过了角落,但我无法使该部分正常工作。

我也想获取标头数据和链接对象,因此我可以用它来发现API的更多部分,并在UI上进行分页。

我需要将搜索作为参数对象传递,因为构建API时,我不知道API使用者希望搜索哪些字段,因此不能将其作为URL的一部分。

c# .net-core asp.net-core-webapi
2个回答
0
投票

无需为此花费大量时间,我的建议是将对象反序列化为具体类型,例如List,而不是IEnumerable(这不是具体类型)。

        return await JsonSerializer.DeserializeAsync<List<BookDisplay>>
                    (await _httpClient.GetStreamAsync($"/api/Books?Author=IanFleming&Style=Spy"), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });

0
投票

这是反序列化问题。 Json数据与您要反序列化的类型不匹配。

这里正在根据您的json数据运行dto类:

public class Rootobject
{
    public Value[] value { get; set; }
    public Link[] links { get; set; }
}

public class Value
{
    public int id { get; set; }
    public string Author { get; set; }
    public string Stye { get; set; }
    public string Title { get; set; }
}

public class Link
{
    public string href { get; set; }
    public string rel { get; set; }
    public string method { get; set; }
}

因此可以使用以下方法进行反序列化:

return await JsonSerializer.DeserializeAsync<Rootobject>
                        (await _httpClient.GetStreamAsync($"/api/Books?Author=IanFleming&Style=Spy"), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });

Visual Studio有很好的方法paste json as classes

© www.soinside.com 2019 - 2024. All rights reserved.