C# – How to delete a file

You can use File.Delete() (in System.IO) to delete a file by specifying its relative or absolute path. Here’s an example: Note: Unlike other methods in the File API, there’s no async version of File.Delete(). If the specified file exists and the permissions are right, then File.Delete() deletes the file as expected. If there’s a problem, … Read more

ASP.NET Core – How to manually validate a model in a controller

Manually validating a model can mean a few different things. It depends on what you’re trying to do exactly. Are you trying to validate a model object against its validation attributes? Use TryValidateModel(). Are you trying to do validation logic manually (instead of using validation attributes)? You can add errors to ModelState in that case. … Read more

Get data from an API in React

In this article, I’ll show how to make a request to an API to get data and then display it in a React component. This can be broken down into three steps: Here’s a working code example of how to do this: Note: Install the axios package with ‘npm install axios’. If you prefer to … Read more

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

How to set the Content-Type header in Postman

When you want to use Postman to send a request with content in the Body, you have to first select a content type option (none, form-data, etc…). When you select the type and add content, Postman automatically generates the Content-Type header. You can see the auto-generated Content-Type header in the Headers tab. The following table … 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