.NET 5: Exploring System.Net.Http.Json namespace
.NET 5 brings interesting new features. In this article I will introduce you a new namespace that provides many extension methods for HttpClient and HttpContent that perform serialization and deserialization using System.Text.Json: Here is System.Net.Http.Json !
The content of this article is taken from Microsoft’s documentation, + my content (samples) in addition.
There are three classes in that namespace:
- HttpClientJsonExtensions which provides extension methods to send/receive HTTP content as JSON
- HttpContentJsonExtensions which provides extension methods to read and then parse the HttpContent from JSON
- JsonContent which provides HTTP content based on JSON
Let’s take a look at some pieces of code together to see how it works, but before we’ll need to download the following required package:
PM> Install-Package System.Net.Http.Json -Version 5.0.0-rc.1.20451.14
That class includes three methods (each having several overloads that I will not describe):
- GetFromJsonAsync which sends a GET request to the specified Uri and return the value resulting from deserialize the response body as JSON asynchronously
- PostAsJsonAsync which send a POST request to the specified Uri containing a value serialized as JSON in the request body asynchronously
- PutAsJsonAsync which send a PUT request to the specified Uri containing a value serialized as JSON in the request body
NB: For now I have no idea why there is no method for PATCH, something like PatchAsJsonAsync.
Here is a code sample that describes their usage, and how we had to do before .NET 5:
As you can see, the HttpClient usage is very lighter and simpler.
That classes contains only one method: ReadFromJsonAsync which has two overloads (I won’t describe each). That extension methods reads the HTTP content and return the value resulting from deserialize the content as JSON asynchronously.
Once again it’s much simpler !
You’ll need to use that extension method if you don’t prefer to use the HttpClientJsonExtensions class, ReadFromJsonAsync is made to do the same thing as GetFromJsonAsync but it applies on HttpContent which is returned by SendAsync.
public sealed class JsonContent : System.Net.Http.HttpContent
So what’s new with JsonContent ? The answer is: Create method which is not an extension method. This method allows to create an HttpContent based on JSON for instantiating an HttpRequestMessage to be passed to SendAsync method. This could be used as an alternative to PostAsJsonAsync or PutAsJsonAsync extension methods or to compensate for the missing PatchAsJsonAsync extension method.
System.Net.Http.Json brings some interesting features, all based on System.Text.Json which is a most performant assembly to serialize / deserialize JSON. I encourage you to rework your HttpClients in order to use these new features of .NET 5. Have fun and Happy coding 🙂