вызов метода консоли ядра .net - PullRequest
0 голосов
/ 07 октября 2019

Я пытаюсь вызвать метод из метода Main () основного консольного приложения .net, который должен отображать два свойства из внешнего API, но консоль отображает только Hello World и никаких других данных результатов, я также хочуконсоль оставаться на месте и не исчезать с экрана. Все указатели справки приветствуются и заранее благодарны!

UserItem.cs -

public class UserItem
{
    public UserItem(string name, string url)
    {
        Name = name;
        Url = url;
    }
    public string Name { get; set; }
    public string Url { get; set; }
}

Program.cs -

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        GetUser();            
    }
    // retrieve all.
    public static async void GetUser()
    {
        //baseUrl
        string baseUrl = "http://pokeapi.co/api/v2/pokemon/";
        try
        {
            // HttpClient implements a IDisposable interface.
            using (HttpClient client = new HttpClient())
            {
                //initiate Get Request (await will execute the using statement in order).
                using (HttpResponseMessage res = await client.GetAsync(baseUrl))
                {
                    //get content from response, then convert it to a c# object.
                    using (HttpContent content = res.Content)
                    {
                        //assign content to data variable by converting into a string using await.
                        var data = await content.ReadAsStringAsync();
                        //If the data is not null log convert the data using newtonsoft JObject Parse class method.
                        if (content != null)
                        {
                            //log data object in the console
                            Console.WriteLine("data------------{0}", JObject.Parse(data)["results"]);
                        }
                        else
                        {
                            Console.WriteLine("NO Data----------");
                        }
                    }
                }
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine("Exception Hit------------");
            Console.WriteLine(exception);
        }
    }

}

1 Ответ

1 голос
/ 07 октября 2019
using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //Waits the API response
            GetUser().Wait();

            //Waits until a key is pressed.
            Console.ReadKey();
        }
        // retrieve all.
        public static async Task GetUser()
        {
           //...
        }

    }
}
...