.NET 7: Simplify Patch requests with PatchAsJsonAsync extension
Introduction
Until .NET 6, it was possible to use an easy to use extension on HTTP clients for POST and PUT requests. It was possible to use the PostAsJsonAsync and PutAsJsonAsync methods that took a URL and an object that the method (the internal one) would serialize to JSON without developer intervention. Unfortunately, this was not possible on HTTP Patch requests. .NET 7 fixes this and I will show you how.
Before and since .NET 7
Previously it was necessary to serialize the object passed in the body of the request by instantiating an object of type StringContent which required three parameters:
- The serialized object in text format, usually in JSON (the standard)
- The encoding, usually UTF8
- The media type, usually JSON (the standard of use)
This gave the following code:
.NET 7 fixes this by bringing a new method: PatchAsJsonAsync, the latter works like PostAsJsonAsync and PutAsJsonAsync, by encapsulating the serialization, which gives:
Much simpler isn’t it ? 😉