简体   繁体   中英

Consuming JSON from another API in own .NET Core API

For my project at the company I do an internship at, I was tasked with creating an API that could manage multiple admin-interfaces of other services. These admin-interfaces are controlled by API endpoints.

They asked me to start with the admin API of their "forms engine". An API which allows "tenants" (people that have a contract to use said engine) to make surveys and such. My task is to make an interface that can get the tenants, create and delete. The usual.

Thing is, I'm not getting any output from the API, even though I should. This is also the first time I am consuming JSON in .NET Core so I might be missing something.

The data structure for the /admin/tenants endpoint looks as follows:

{
    "_embedded": {
        "resourceList": [
            {
                "id": "GUID",
                "name": "MockTenant1",
                "key": "mocktenant1",
                "applicationId": "APPGUID",
                "createdAt": "SOMEDATE",
                "updatedAt": "SOMEDATE"
            },
            {
                "id": "GUID",
                "name": "MockTenant2",
                "key": "mocktenant2",
                "applicationId": "APPGUID",
                "createdAt": "SOMEDATE",
                "updatedAt": "SOMEDATE"
            }
        ]
    },
    "_page": {
        "size": 10,
        "totalElements": 20,
        "totalPages": 2,
        "number": 1
    },
    "_links": {
        "self": {
            "href": "SOMELINK"
        },
        "first": {
            "href": "SOMELINK"
        },
        "last": {
            "href": "SOMELINK"
        },
        "next": {
            "href": "SOMELINK"
        }
    }
}

So I let Visual Studio automatically create following structure from said JSON:

    public class Rootobject
    {
        public _Embedded _embedded { get; set; }
        public _Page _page { get; set; }
        public Dictionary<string, Href> _links { get; set; }
    }

    public class _Embedded
    {
        [JsonProperty("resourceList")]
        public Tenant[] tenantList { get; set; }
    }

    public class Tenant
    {
        public string id { get; set; }
        public string name { get; set; }
        public string key { get; set; }
        public string applicationId { get; set; }
        public DateTime createdAt { get; set; }
        public DateTime updatedAt { get; set; }
    }

    public class _Page
    {
        public int size { get; set; }
        public int totalElements { get; set; }
        public int totalPages { get; set; }
        public int number { get; set; }
    }
    public class Href
    {
        public string href { get; set; }
    }

I changed the Classname from ResourceList to Tenant, because that's what it is. So, now coming to the code that gets the tenants:

        public async Task<List<Tenant>> getTenants()
        {
            List<Tenant> tenantList = new List<Tenant>();
            if (accessToken == "" || validUntil < DateTime.Now)
            {
                getNewAccessToken();
            }
            using (var request = new HttpRequestMessage(new HttpMethod("GET"), baseUrl + "admin/tenants"))
            {
                request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}");
                request.Headers.TryAddWithoutValidation("apikey", apiKey);
                using (var response = await httpClient.SendAsync(request))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        try
                        {
                            Rootobject result = JsonConvert.DeserializeObject<Rootobject>(await response.Content.ReadAsStringAsync());
                            tenantList.AddRange(result._embedded.tenantList);
                        }
                        catch (Exception ex)
                        {
                            Debug.Write(ex);
                        }
                    }
                }
            }
            foreach (Tenant t in tenantList)
            {
                Debug.Write(t);
            }
            return tenantList;
        }

The Debug.Write(t) and the return give me nothing. It is an empty list. Anybody have any idea as to why this is, and what I can do about it?

Thanks in advance and kind regards Lennert

  1. Property name must match json object name either directly or via JsonPropertyAttribute
public class _Embedded
{
    [JsonProperty("resourceList")]
    public List<Tenant> tenantList { get; set; }
}
  1. You may optimize the hrefs
public class Rootobject
{
    public _Embedded _embedded { get; set; }
    public _Page _page { get; set; }
    public Dictionary<string, Href> _links { get; set; }
}

public class Href
{
    public string href { get; set; }
}
  1. HttpResponseMessage is IDisposable
using(var response = await httpClient.SendAsync(request))
{
    // reading response code
}
  1. As per Documentation

HttpClient is intended to be instantiated once per application, rather than per-use.

remove

using (var httpClient = new HttpClient())

and add field

private static readonly HttpClient httpClient = new HttpClient();
  1. foreach(Tenant tenant in result._embedded.tenantList) can be optimized
foreach(Tenant tenant in result._embedded.tenantList)
{
    tenantList.Add(tenant);
}

Or single line

tenantList.AddRange(result._embedded.tenantList);

Or simply

foreach(Tenant t in result._embedded.tenantList)
{
    Debug.Write(t);
}
return result._embedded.tenantList;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM