Search code examples
c#asp.net-web-apiclass-library

how to properly use HttpClient wrapped as a Class Libary


In my C# app I need to have 2 distinct parts:
1) a Class Library, which wraps HttpClient, takes parameters, such as URI, and a JSON object to be POSTED, and invokes the POST method on an instance of HttpClient:

static async Task CreateCustomer()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://10.211.55.2:8080/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Accept", "application/json");

                var customer = new Customer() { Name = "Gizmo",  Address = "123 Widget lane" };
                var response = await client.PostAsJsonAsync("/api/customer", customer);
                var p = response;
            }
        }

2) A Windows Console app, which imports this Class Library, and invokes this CreateCustomer method, passing the actual parameter values for the URI and the Customer JSON object:

static async Task EnvokeCreateCustomer()
        {
            Customer customer = new Customer {Name="",Address="" };
            var URI = "http://my_api:8080/Customer";
            RestClient.Client restClient = new RestClient.Client();
            restClient.CreateCustomer(URI, customer);
        }

This code runs, but it is not event hitting my API, blows right passed it, and does nothing. Same issue with the GET API.

Is there a proven way to create such Class Libraries, which can be invoked by a Console app?


Solution

  • You don't await the method call:

    await restClient.CreateCustomer(URI, customer);
    

    Depending on the application host this may or may not make a noticeable difference. In a console application, where the application may simply do its thing and immediately terminate, it makes an enormous difference.

    Not to mention any errors received in the process may go entirely unnoticed if the call is not awaited. So it's possible that there is a problem and it's trying to tell you what the problem is, but your code is simply ignoring it.

    Surely there's a compiler warning pointing this out. Never ignore compiler warnings.


    Side note: How does this code even compile? This:

    restClient.CreateCustomer(URI, customer);
    

    can't be calling this:

    static async Task CreateCustomer()
    

    If what you're showing us isn't your actual code, then all bets are off as far as answers go.