SHARE:

.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 ? 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: