(C# ASP.NET Core) Call a POST Web API From a C# WPF Application

This tutorial continues from the previous tutorial. We have discussed most of the parts there. So please go through the previous tutorial for a continuity. Now we shall call a POST WebApi from our Wpf Application, and create a new record.
(Rev. 05-Oct-2022)

Categories | About |     |  

Parveen,

Objective of this tutorial

We shall use a form on the Wpf application to obtain the name and fees of a new doctor record. When the user clicks the save button, a web api call is made to the POST api, and a new record is created in the server side.

Let us have a look at the web api that we have to call. Open the ASPNET Core web api project that we have been completing in this chapter. This project, as well as the wpf application is provided in the downloads of this chapter.

Locate the program.cs file and double click to open it! Scroll to the part that you are seeing here.

// program.cs file of the webapi project 
// the project is in the downloads attached to this video 
app.MapPost("/doctor", async (MyApiContext ctx, DoctorDTO doctor) =>
{

  Doctor doc = new Doctor()
  {

    Name = doctor.Name,
    Fees = doctor.Fees,
    EMail = "assign-any"
  };

  ctx.Doctors.Add(doc);

  // success assumed for tutorial purposes 
  await ctx.SaveChangesAsync();

  return Results.Created($"/doctor/{doctor.Id}", new DoctorDTO(doc));

});

The POST webapi receives a DoctorDTO as a parameter. The api can be called through the route /doctor.

Run the application and allow the home page to open. This ensures that the server starts running.

Video Explanation (see it happen!)

Please watch the following youtube video:

The Wpf Project

Run the project so that we can visually see the whole thing. As you can see we have a form for obtaining the data of a new record. There is a save button also. Let's have a look at the event handler for the save button.

Open the solution explorer of the wpf project. Locate the MainWindow.xaml.cs file and open it. This is the file - and we have discussed various parts in the previous tutorial. Now we can scroll to the event handler for the save button.

// MainWindow.xaml.cs 
// see the linked downloads for the wpf project 
private async void btnSaveDoctor_Click(object sender, RoutedEventArgs e)
{

  string message = string.Empty;

  // validate input data 
  if (
    !String.IsNullOrEmpty(txtDoctorName.Text)
      &&
    int.TryParse(txtFees.Text, out int n)
  )
  {

    using (HttpClient client = new HttpClient())

    {

      // dto to be POST-ed 
      var doctor = new DoctorDTO()
      {

        Fees = Convert.ToInt32(txtFees.Text),
        Name = txtDoctorName.Text
      };

      try
      {

        HttpResponseMessage response =
               await client.PostAsJsonAsync($"{SvcIP}", doctor);

        response.EnsureSuccessStatusCode();

        message = await response.Content.ReadAsStringAsync();

      }

      catch (Exception ex)
      {

        message = ex.Message;

      }

    }

    LoadAllDoctors();

  }

  else 
  {

    message = "Please enter valid data.";

  }

  MessageBox.Show(this, message, "Message", MessageBoxButton.OK);

}

// ... remaining code not shown, being not relevant here 

First we have made a few validation checks. Then we have used the HttpClient class - this class is the recommended class for WebApi communication.

A DoctorDTO is created for posting to the web api. The PostAsJsonAsync method of the HttpClient class is used for making the actual call.

The response is read by using the ReadAsStringAsync function. This response is shown in a messagebox so that we can verify the result of this call.

Run this application. Allow the window to open. Enter some data in the textboxes. Click the save button, and wait for the response. We verify that the server responds with the json for the newly created record. Everything is working as expected - thanks!


This Blog Post/Article "(C# ASP.NET Core) Call a POST Web API From a C# WPF Application" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.