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

This tutorial explains how a GET web api can be called from a C++ WinRT application. I have chosen WinRT type because it contains a lot many pre-written functions that simplify internet access and json parsing. I won't be able to explain the details of a WinRT setup, so I have already created a WinRT console application that connects to our web api, and then obtains a string from the application, and then parses the json contained in that string. The c++ project has been provided in the downloads attached to this course.
(Rev. 19-Mar-2024)

Categories | About |     |  

Parveen,

The Objective of this Tutorial

Let me first explain the objective of this tutorial.

We will make a GET request to a web api that sends a json consisting of two properties - name and fees. After that we shall parse that json and display the extracted properties.

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.

// the WebApi that we shall call 

// our URL shall be /doctor/1 

// find record by ID 
app.MapGet("/doctor/{id}", async (MyApiContext ctx, int id) =>
{

  if (await ctx.FindAsync<Doctor>(id) is Doctor doctor)
  {

    return Results.Ok(new DoctorDTO(doctor));

  }

  else 
  {

    return Results.NotFound();

  }

});

This web api responds to a route template - /doctor/{id} - and sends a json of the record corresponding to the id extracted from the route template.

We shall make a call for a record of id = 1. So our target address would be /doctor/1

// target URL address 

http://localhost:port/doctor/1

Run the Web Application first

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.

// main.cpp file (see the attached course downloads) 

// pre-compiled header 
#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> 

// std iostream 
#include <iostream>

using namespace winrt;

using namespace Windows::Foundation;

using namespace Windows::Web::Http;

using namespace Windows::Data::Json;

int main()
{

  init_apartment();

  Uri requestUri{ L"https://localhost:44387/doctor/1" };

  HttpClient httpClient{};

  HttpResponseMessage httpResponseMessage;

  hstring httpResponseBody;

  try
  {

    // Send the GET request. 
    httpResponseMessage = httpClient.GetAsync(requestUri).get();

    httpResponseMessage.EnsureSuccessStatusCode();

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

  }

  catch (winrt::hresult_error const& ex)
  {

    httpResponseBody = ex.message();

    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.

A try block contains the statements for sending a GET 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 name and fees are displayed successfully! (see the attached video also)

Thanks!


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