(C# ASP.NET Core) Calling a POST WebApi from a C++ WinRT App

This tutorial explains how a POST web api can be called from a C++ WinRT application. I have created a WinRT console application that connects to, and posts a json string to a POST web api, and then obtains a string response from the application, and then parses the json contained in that string. The c++ project is available in your downloads.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

The Objective of this Tutorial

Let me first explain the objective of this tutorial.

The central idea of this tutorial is that we have a client-side application that will post the name and fees of a doctor - the POSTing will be to a POST type of web-api. This web api will create a new record and send a response to our application. The response string will be decoded and shown on the console window of our C++ WinRT application.

Video Explanation (see it happen!)

Please watch the following youtube video:

The WebApi that we have to call

Let us first have a look at the WebApi that we have to call. Open the project that we have been discussing in this chapter, and locate the program.cs file. Double-click and open this file. Scroll to the part you are seeing here.

Put a break-point somewhere in the body of the web-api. It will help us verify if our client is able to reach this specific web api.

// the WebApi that we shall call 
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));

});

This is a POST type of web api, and therefore, it has to create a new record. The calling client has to POST the data for the record - and ASPNET Core will pack this data into a DoctorDTO argument.

EF Core is next used to create a new record and save the changes to the database.

Finally, a 201 created json is sent back to the caller. We have discussed this API in detail in one of our previous chapters. You can refer that for finer details of this API.

// target URL address 

http://localhost:port/doctor

Run the Application

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

Take note of the URL and the port number - we will need it in the next step.

The WinRT Application Client

Create a console based C++ winrt application and open the solution explorer. Locate the main.cpp file in the solution explorer that you are seeing here. This project is available in the downloads attached to this video.

Double click and open the main.cpp file.

#include "pch.h"

// pch.h contains 
// #include <winrt /Windows.Foundation.h> 
// #include <winrt /Windows.Foundation.Collections.h> 
// #include <winrt /Windows.Web.Http.Headers.h> 
// #include <winrt /Windows.Data.Json.h> 
#include <iostream>

using namespace winrt;

using namespace Windows::Foundation;

using namespace Windows::Web::Http;

using namespace Windows::Data::Json;

using namespace Windows::Storage::Streams;

int main()
{

  init_apartment();

  Uri requestUri
  {

    //-your-webapi-
    L"https://localhost:44387/doctor"
  };

  HttpClient httpClient{};

  HttpResponseMessage httpResponseMessage;

  hstring httpResponseBody;

  // Construct the JSON to post. 
  HttpStringContent jsonContent(
       L"{ \"name\": \"doc 3\", \"fees\": 300 }",
       UnicodeEncoding::Utf8,
       L"application/json"
  );

  try
  {

    // Post the JSON and wait for a response. 
    httpResponseMessage = httpClient.PostAsync(requestUri, jsonContent).get();

    httpResponseMessage.EnsureSuccessStatusCode();

    httpResponseBody = httpResponseMessage.Content().ReadAsStringAsync().get();

  }

  catch (winrt::hresult_error const& ex)
  {

    httpResponseBody = ex.message();

    std::wcout << "EXCEPTION: " << httpResponseBody.c_str() << std::endl;

    return -1;

  }

  // parse the string from server 
  JsonValue jsonValue = JsonValue::Parse(httpResponseBody);

  // extract name and fees 
  hstring Name = jsonValue.GetObject().GetNamedString(L"name");

  int Fees = (int)jsonValue.GetObject().GetNamedNumber(L"fees");

  // display 
  std::wcout << L"Doctor: " << Name.c_str() << std::endl;

  std::wcout << L"Fees: " << Fees << std::endl;

  return 0;

}

These are the files that have been included through the pch.h precompiled header file.

Next we have the well-known header for iostream.

A Uri is created on the basis of the URL for the web api.

An HttpClient will help us communicate with the server, and the response string will be collected as an hstring.

Next we have created an HttpStringContent in json format.

A try block contains the statements for sending a POST request and receiving the response body.

JsonValue is used to parse the string.

GetNamedString and GetNamedNumber are used to extract the name and fees of the received entity.

Lastly, the data is displayed.

Run the application now!

We verify that the break point in the ASPNET Core application is hit! and we also verify that the name and fees are received back successfully at the client side console window!

Thanks!


This Blog Post/Article "(C# ASP.NET Core) Calling a POST WebApi from a C++ WinRT App" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.