question

Andrej avatar image
0 Votes"
Andrej asked YijingSun-MSFT edited

Documentation for working with REST services, configuring HttpClient

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.

dotnet-csharpdotnet-aspnet-core-webapipartner-center-api
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I would start by reading the official documentation. If you have a specific problem then share enough code to illustrate the problem and clearly explain how you expect the code to function.


HttpClient Class
Make HTTP requests using IHttpClientFactory in ASP.NET Core
Use IHttpClientFactory to implement resilient HTTP requests


1 Vote 1 ·

1 Answer

cooldadtx avatar image
1 Vote"
cooldadtx answered

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;
}
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.