C# – How to read problem details JSON with HttpClient

Problem details (RFC7807) is a standardized error response format that has a Content-Type of application/problem+json, an error response code (i.e. 400 – Bad Request), and has a response body that looks like this: This can be extended to include any number of properties. The example shown above comes from the default way ASP.NET Core returns … Read more

C# – Convert an object to JSON and vice versa

The simplest way to convert an object to JSON (serialization) is to use the built-in System.Text.Json.JsonSerializer: This serializes the Movie object to JSON using the default serialization settings (notice it’s not pretty printed by defualt). Here’s the JSON this produces: To do the opposite – convert a JSON string to an object (deserialization) – use … Read more

C# – Deserializing JSON with quoted numbers

There are two ways to represent numbers in JSON: as number literals (ex: 123) or as quoted numbers (ex: “123”). In this article, I’ll explain how quoted numbers are handled during deserialization in Newtonsoft and System.Text.Json and how to change the behavior. At the end, I’ll show how to write quoted numbers during serialization. Quoted … Read more

ASP.NET Core – How to unit test your middleware class

There are three requirements for unit testing a middleware class: Mock out RequestDelegate by defining a lambda that returns a Task (Task.FromException, Task.FromResult, or Task.FromCanceled). Mock out HttpContext by using DefaultHttpContext. The middleware function needs to be awaited, so your unit test needs to be defined with async Task. Here’s an example: This is a … Read more

ASP.NET Core – How to change the JSON serialization settings

System.Text.Json is the default JSON serializer in ASP.NET Core. It uses the following default serialization settings: To change the settings at the service level for all controllers, call AddJsonOptions() in Startup.ConfigureServices() like this: Note: This example is passing in JsonStringEnumConverter, which makes JsonSerializer use the enum name instead of enum value. When you change the … Read more

C# – Get and send JSON with HttpClient

The simplest way to get and send JSON with HttpClient is to use the GetFromJsonAsync() and PostAsJsonAsync() extension methods found in System.Net.Http.Json, like this: Note: You have to install the System.Net.Http.Json nuget package if you’re using a framework version before .NET 5. These extension methods use System.Text.Json for serialization. They simplify things by abstracting away … Read more