ASP.NET Core – How to unit test a custom InputFormatter

In this article, I’ll show how to unit test a custom InputFormatter. The main thing to test is the output of the ReadRequestBodyAsync() method. To test this, you have to pass in an InputFormatterContext object containing the request body. As an example, I’ll show how to unit test the following ReadRequestBodyAync() method: Note: This parses … Read more

ASP.NET Core – How to receive requests with XML content

Receiving requests with XML content is straightforward. You have to register the built-in XML InputFormatter (otherwise you get 415 – Unsupported Media Type errors). When a request comes in with an XML Content-Type (such as application/xml), it uses this InputFormatter to deserialize the request body XML. In this article, I’ll show step-by-step how to receive … Read more

ASP.NET Core – How to receive a request with text/plain content

When a request comes in and your action method has parameters, the framework tries to find the appropriate InputFormatter to handle deserializing the request data. There’s no built-in text/plain InputFormatter though, so when you send a request with text/plain content, it fails with a 415 – Unsupported Media Type error response. In this article, I’ll … Read more

ASP.NET Core – Only one parameter per action may be bound from body

When you have multiple parameters on an action method that are bound to the request body (implicitly or explicitly), you get the following fatal exception upon starting the web API: System.InvalidOperationException: Action ‘RecipeController.Post’ has more than one parameter that was specified or inferred as bound from request body. Only one parameter per action may be … Read more

C# – How to send synchronous requests with HttpClient

In .NET 5 and above, you can use the HttpClient Sync API methods – Send() and ReadAsStream() – to send HTTP requests synchronously (as opposed to resorting to sync-over-async). Here’s the steps for doing this: HttpClient was originally designed for async requests and has many async convenience methods (like GetAsync() and ReadAsStringAsync()). There aren’t sync … Read more

C# – Parse a comma-separated string into a list of integers

Let’s say you want to parse a comma-separated string into a list of integers. For example, you have “1,2,3” and you want to parse it into [1,2,3]. This is different from parsing CSV with rows of comma-separated values. This is more straightforward. You can use string.Split(“,”) to get the individual string values and then convert … Read more

CsvHelper – Header with name not found

When your CSV header names don’t match your property names exactly, CsvHelper will throw an exception. For example, if your header name is “title” and your property name is “Title”, it’ll throw an exception like: HeaderValidationException: Header with name ‘Title'[0] was not found. If you don’t want to (or can’t) change the names to match, … Read more

C# – Manually validate objects that have model validation attributes

You can use the Validator utility class to do manual attribute-based validation on any object, in any project type (as opposed to doing automatic model validation in ASP.NET). To do this, add model validation attributes to your class properties, then create an object and populate it (aka binding), and finally execute manual validation with the … Read more

C# – ConfigurationSection.Get() returns null

When you use ConfigurationSection.Get() to load an object from appsettings.json, it returns null if the section doesn’t exist. Since you’re probably not expecting this to be null, this can lead to problems surfacing in unexpected places, such as getting a NullReferenceException: Note: If you’re using ASP.NET Core, you’ll be referring to the config via builder.Configuration … Read more

C# – Parsing a CSV file

In this article, I’ll show how to parse a CSV file manually and with a parser library (CsvHelper). Let’s say you have the following CSV file: To manually parse this, read the file line by line and split each line with a comma. This gives you a string array containing the fields that you can … Read more

C# – How to disable ModelStateInvalidFilter

There are two options for disabling ModelStateInvalidFilter: You’d do this when you want to manually perform model validation. I’ll show both options below. Disable ModelStateInvalidFilter globally To disable ModelStateInvalidFilter for *all* actions, set SuppressModelStateInvalidFilter=true in ConfigureApiBehaviorOptions, like this: Disable ModelStateInvalidFilter for specific actions To disable ModelStateInvalidFilter selectively, you can implement an IActionModelConvention attribute that removes … Read more

C# – JSON deserializer returns null properties

Let’s say you have the following JSON: When you go to deserialize it, you notice that all or some of its properties are null (or default for value types): This outputs the following (because person.Name is null and person.Pets is 0): The data is definitely there, so why did it set these properties to null … Read more

C# – How to deconstruct an object

Deconstructing an object means assigning its properties to several variables with a one-liner using deconstruction assignment syntax (also referred to as destructuring or unpacking). Here’s an example of deconstructing an object: This outputs the following: Several built-in types already support deconstruction – such as tuples, dictionary (KeyValuePair), and records. You can enable deconstruction for any … Read more

ASP.NET Core – Logging requests and responses

The simplest way to log requests/responses is to use the HTTP Logging middleware (added in v6). This is configurable, so you can make it suit your needs. If you need more control, you can add your own middleware instead. To use the HTTP Logging middleware, call UseHttpLogging() in your initialization code: Then add Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware to … Read more

C# – Suppress nullable warnings (CS8602)

Sometimes the compiler shows unhelpful nullable warnings. Here’s an example of it showing warning CS8602, when it’s obvious to any human reading the code that you’re doing a null-check already (in ThrowIfNull()): Besides disabling the Nullable feature, there are two ways to suppress nullable warnings on a case-by-case basis: I’ll show both options below. Option … Read more

C# – Ignore null properties during JSON serialization

By default, null properties are included during JSON serialization like this: There are two ways to ignore null properties: In this article, I’ll show examples of these two ways to ignore null properties. I’ll show how to do it with System.Text.Json and Newtonsoft. Ignore null properties with System.Text.Json Use JsonIgnoreCondition.WhenWritingNull to ignore null properties. You … Read more

Using Visual Studio props files

When you want multiple projects in a solution to use the same project settings (some or all), you can put the settings in a shared props file. There are two options: I’ll show both options below. Note: You can also use a combination of these two options. Option 1 – Use Directory.Build.props You can use … Read more

C# – How to treat warnings like errors

Warnings are easy to ignore and forget about, which isn’t good. They point out potential problems that you might want to fix. To make it easier to pay attention to warnings, you can treat them like errors. You can choose which warnings to treat like errors by using settings in the project file (or in … Read more