Documentation for working with REST services, configuring HttpClient

Andrej 221 Reputation points
2021-11-10T14:35:07.207+00:00

I have to work with REST services. Such operations as make requests/responses, sending/receiving files, in JSON and in XML formats. Tell me please, documentation, how to configuring and use HttpClient in Asp.Net Core applications.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,154 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,226 questions
Microsoft Partner Center API
Microsoft Partner Center API
Microsoft Partner Center: A Microsoft website for partners that provides access to product support, a partner community, and other partner services.API: A software intermediary that allows two applications to interact with each other.
313 questions
{count} votes

Accepted answer
  1. Michael Taylor 47,806 Reputation points
    2021-11-10T15:18:29.283+00:00

    That's a lot to ask for in a forum post. I think the best option is to point you to the documentation that has examples. But please note there are quite a few variants on how to do things so you will likely need to make some adjustments to fit the needs of the specific service you are calling.

    If you need to call a REST API then you'll use HttpClient for that. This class takes the base URL you want to call and then you use the methods it exposes to fetch data. Word of warning here, HttpClient (at least in .NET Framework) should be created once per base URL and then reused. Therefore it is generally recommended that you create the client in your app startup (or lazily) only once. I'm just showing the code here without that logic put in.

       //The URL must end with a slash....  
       var client = new HttpClient() { BaseAddress = new Uri("https://api-weather.tempuri.org/") };  
         
       //Making an assumption here that this is an async method  
       //Call the 'today' endpoint to get today's weather and return the string  
       using (var response = await client.GetStringAsync("today"))  
       {  
           //You now have the response as a string in whatever format you need  
       };  
    

    The HttpClient documentation I linked to has a full example of this.

    Making POST/PUT requests is similar. The data format you get back depends upon the API and what you request. To indicate that you want JSON or XML (or whatever) you set the Accept header when you create the client.

       var client = new HttpClient(...);  
       client.DefaultRequestHeaders.Add("Accept", "application/json");  
    

    Now the API will return all the data in JSON. If you need to override this for specific API calls (such as downloading a file) then you will need to set the request header on the message directly before you send it. But that is an advanced situation.

    To actually convert the JSON back to a typed object you'll need a serializer. If you're using ASP.NET then that is likely JSON.NET. If you're using ASP.NET Core then it'll be System.Text.Json instead. They are basically identical except for the type you use. For ASP.NET Core there are extension methods to retrieve and convert the JSON in a single call but you need to add the System.Net.Http.Json Nuget package to your project. This article has a good example.

    Having said all that, I personally recommend that you create a simple wrapper class around each API service you intend to call. Let the wrapper handle the HTTP stuff for you. There are tools that can auto-generate this for you. For example if the API uses OpenAPI (most do) then Visual Studio has a tool to do that. Right click your project and select Add \ Connected Service. Then point it to the URL of the API and it'll auto-generate a .NET class to talk to that API for you. That is by far the easiest approach but produces bloated code in my opinion. Here's what something like that might look like though.

       public class WeatherClient  
       {  
          public WeatherClient ( string url )  
          {  
             if (!url.EndsWith("/"))  
                url += "/";  
         
             _client = new HttpClient() { BaseAddress = new Uri(url) };  
          }  
          public WeatherClient ( HttpClient client )  
          {  
             _client = client;  
          }  
         
          //Weather is a type that matches the structure of what the API returns  
          public Task<Weather> TodayAsync ( CancellationToken cancellationToken = default )  
          {  
             //Using System.Net.Http.Json package  
             return _client.GetFromJsonAsync<Weather>("today", cancellationToken);  
          }  
         
          private readonly HttpClient _client;  
       }  
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful