Create a rest client

Posted by ugh82 on Wed, 09 Mar 2022 16:48:50 +0100

Create a rest client


. NET Core Download

Visual Studio Code

Create application

Create a separate folder and run console commands

dotnet new console --name WebAPIClient

Add a new dependency

Applications can handle JSON responses.

dotnet add package System.Text.Json

Make a web request

First, open Program. In the project directory CS file, and then add the following methods to the Program class:

private static async Task ProcessRepositories()

You need to add the using instruction at the top of the Main method so that the C# compiler can recognize it Task Type:

using System.Threading.Tasks;
  1. Update the Main method to call the ProcessRepositories method

  2. The ProcessRepositories method returns a task and should not exit the program before this task is completed

    Add the async modifier and change the return type to Task

  3. In the body of the method, add a call to ProcessRepositories. Add the await keyword to the method call:

static async Task Main(string[] args)
    await ProcessRepositories();

Generated a program that does not perform any operation but has asynchronous function

Improve web requests

  1. First, we need an object that can retrieve data from the Web; Available HttpClient Do this. This object is responsible for processing requests and responses. In Program An instance of this type is initialized in the Program class in the. CS file.

    namespace WebAPIClient
        class Program
            private static readonly HttpClient client = new HttpClient();
            static async Task Main(string[] args)
  2. Let's go back to the ProcessRepositories method and populate its first version:

    private static async Task ProcessRepositories()
            new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
        client.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");
        var stringTask = client.GetStringAsync("");
        var msg = await stringTask;
  3. In order for the compilation to proceed smoothly, two new using instructions need to be added at the top of the file:

    using System.Net.Http;
    using System.Net.Http.Headers;

Processing JSON results

  1. Convert the corresponding JSON response into a C# object
using System;

namespace WebAPIClient
    public class Repository
        public string name { get; set; }

Add the above code to the new file "repo.cs". This version of the class represents the simplest path to handle JSON data

  1. Use a serializer to convert JSON to C# objects. Replace the pair in the ProcessRepositories method with the following line GetStringAsync(String) Call to:

    var streamTask = client.GetStreamAsync("");
    var repositories = await JsonSerializer.DeserializeAsync<List<Repository>>(await streamTask);

    Add namespace at the top of the file

    using System.Collections.Generic;
    using System.Text.Json;
  2. Displays the name of each repository

    foreach (var repo in repositories)
  3. Compile and run the application. Will print to The name of the repository for. NET Foundation.

Control serialization

  1. Before adding more features, let's deal with the name attribute by using the [JsonPropertyName] attribute. Yes, repo The name field in CS declares the following changes:

    //using System.Text.Json.Serialization;
    public string Name { get; set; }

    Change means that changes need to be used in program CS to write the code for each repository Name:


    Run dotnet run to see the output

  2. The ProcessRepositories method can perform asynchronous work and return a set of repositories. We will use this method to return list < repository >, and move the code used to write the information to the Main method.

    private static async Task<List<Repository>> ProcessRepositories()

    Then, after processing the JSON response, only return to the repository:

    var streamTask = client.GetStreamAsync("");
    var repositories = await JsonSerializer.DeserializeAsync<List<Repository>>(await streamTask);
    return repositories;

    The compiler will generate a task < T > object that returns content because you have marked this method async. Then, we will modify the Main method to capture these results and write each repository name to the console. Now, the Main method is as follows:

    public static async Task Main(string[] args)
        var repositories = await ProcessRepositories();
        foreach (var repo in repositories)

Read details

  1. Handle other properties in JSON packets sent by GitHub API

  2. Add some other simple types to the Repository class definition. Add these attributes to this class:

    public string Description { get; set; }
    public Uri GitHubHomeUrl { get; set; }
    public Uri Homepage { get; set; }
    public int Watchers { get; set; }

    After adding these elements, update the Main method to display them:

    foreach (var repo in repositories)
  3. Let's add information about the last push operation. This information is formatted in the JSON response as follows:


    The format is coordinated universal time (UTC), so you will get one DateTime Value of the value Kind Attribute is Utc . If you prefer dates in time zones, you need to write custom conversion methods. First, define a public attribute, which will save the UTC representation of date and time in the Repository class, and define a LastPush readonly attribute, which returns the date converted to local time:

    public DateTime LastPushUtc { get; set; }
    public DateTime LastPush => LastPushUtc.ToLocalTime();

    Add another output statement in the console, and then you can build and run the application again:


This article is composed of one article multi posting platform ArtiPub Automatic publishing