Home > database >  How do I create a REST client in C#?
How do I create a REST client in C#?

Time:07-23

This is the code of my .NET core 3.1 console application:

using System.Net.Http.Headers;
using NumbersConsole.Models;

namespace NumbersConsole
{
    class Program
    {
        static HttpClient client = new HttpClient();

        static void ShowcaseNumber(NumberModel numberModel)
        {
            Console.WriteLine("Number: "   numberModel.Number.ToString());
            Console.WriteLine("Fact: "   numberModel.Text);
            Console.ReadLine();
        }

        static async Task<NumberModel> GetNumberModelAsync()
        {
            NumberModel number = null;
            var path = new Uri("http://numbersapi.com/41");
            HttpResponseMessage response = await client.GetAsync(path);
            if (response.IsSuccessStatusCode)
            {
                number = await response.Content.ReadAsAsync<NumberModel>();
            }
            return number;
        }
        static void Main(string[] args)
        {
            RunAsync();
        }

        static async Task RunAsync()
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            NumberModel number = new NumberModel();
            number = await GetNumberModelAsync();
            ShowcaseNumber(numberModel);
        }
    }
}

And this is my NumberModel.cs:

namespace NumbersConsole.Models
{
    public class NumberModel
    {
        public string Text { get; set; }
        public int Number { get; set; }
    }
}

Somehow HttpResponseMessage response = await client.GetAsync(path) does not give a response but instead the program just exits.

I have tried using this answer and this article. I have tried multiple variations of this line of code like HttpResponseMessage response = client.GetAsync(path).Result;

Does someone know what is wrong with my code?

CodePudding user response:

As stated in my comment, you aren't awaiting the async method, so the calling thread continues execution in main once the await is hit in your RunAsync method, allowing the application to exit without completing.

As of C# 7.1 you can use an async version of the main method, and since you are targeting .Net Core 3.1, the default is C# 8, so the following should be valid:

static async Task Main(string[] args)
{
    await RunAsync();
}
  • Related