Consume Web API, program need to wait to get respone

dalia.danny

New member
Joined
Mar 1, 2023
Messages
3
Programming Experience
1-3
Hello,

I wrote consume Web API as following,

C#:
      public async Task<List<EditListFinalInv>> GetEditListFinalInvoices_Ifx(string Batch_Id,
      string trans_ref)
        {

            HttpClient client = new HttpClient();
            List<EditListFinalInv> _EditListInterimInv = new List<EditListFinalInv>();

            string url = URLStr + "/GetEditListFinalInvoices_Ifx?Batch_Id=" + Batch_Id
                + "&&trans_ref=" + trans_ref + "";
            client.BaseAddress = new Uri(url);

            HttpResponseMessage response = await client.GetAsync("");
            if (response.IsSuccessStatusCode)
            {
                string content = response.Content.ReadAsStringAsync().Result;
                _EditListInterimInv = JsonConvert.DeserializeObject<List<EditListFinalInv>>(content);
            }
            return _EditListInterimInv;

        }

This code work perfectly. Then, I'm calling it from another routine as following,

C#:
            public async void ExecuteEditListBeforePostingInterimInvoice2(string JobBatchId, string UserId,
string paramData, string ReportName, string modelCurrentJob_Batch_Id, int JobId, string _reportFileName)
        {

 try
            {



// this is Web API calling, need to wait get the result, then proceed to next line
var _objAPI = await objAPI.GetEditListFinalInvoices_Ifx(Send_Batch_Id, TransRefFrom);


// once get the web api response, then proceed


...
.....
.........


}

  catch (Exception ex)

            {

                MessageBox.Show(ex.ToString());

            }



}


How to program, make it wait? Once the Web API response, then go


What happen now, my C# program not waiting Web API response


Please help
 
C#:
 string content = response.Content.ReadAsStringAsync().Result;

Don't do that, and especially not in a method you declared as `async Task`

Do this:

C#:
 string content = await response.Content.ReadAsStringAsync();
 
And then, install Flurl.Http, and just do this:

C#:
public async Task<List<EditListFinalInv>> GetEditListFinalInvoicesAsync(string batchId, string transRef)
  => await STRUrl
    .AppendPathSegment("GetEditListFinalInvoices_Ifx")
    .SetQueryParams(new{ Batch_Id = batchId, trans_ref = transRef } )
    .GetJsonAsync<List<EditListFinalInv>>();

Note: flurl will correctly use HttpCLient for you and do the deserializing, use of correct C# casing, and naming of methods that are asynchronous
 
Last edited:
Re-read post #3 more closely. He said what you need to install.
 
What to install? And what is namespace ?

1677850982315.png


If you never saw this before, this is Nuget Package Manager - right click your project name in solution explorer and choose "Manage Nuget Packages". Make sure youre on Browse tab and package source is nuget.org
 
Back
Top Bottom