ASP.NET Core – Client-side custom validation attributes

I wrote about how to add custom validation attributes. These are used for model validation on the server-side. You can also use these for client-side validation, which I’ll show in this article. 1 – Implement IClientModelValidator The first step is to implement the IClientModelValidator interface in the custom validation attribute class. This has a single … Read more

C# – JSON value could not be converted to System.String

When you send a request to ASP.NET with a JSON body, you get the following exception: System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1. You can’t deserialize JSON to a string. You’re either using a string parameter with [FromBody] or your model has a string … 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

ASP.NET Core – Receive a request with CSV data

There are two ways to receive CSV data in a web API: In this article, I’ll show examples of both of these approaches. I’ll be using the CsvHelper library to parse CSV data into model objects and then do model validation. Note: To use CsvHelper, install the CsvHelper package (Install-Package CsvHelper). Or use whichever parser … 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

ASP.NET Core – Add a custom InputFormatter

Input formatters are used to deserialize the request body to a model object (which is then passed into an action method). There are built-in input formatters for handling JSON and XML. You can add your own input formatter when you want to customize request body deserialization. There are two scenarios where a custom InputFormatter would … 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

ASP.NET Core – Four basic ways to receive parameters

There are four basic ways to receive parameters in an ASP.NET Core Web API: query strings, path parameters, request body, and request headers. I’ll show examples of these below. Query string parameters Let’s say you have two query string keys: name and servings. To get these query string values, add method parameters with names that … 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

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

ASP.NET Core – How to get request headers

There are two ways to get request headers: When a request comes in, the framework loads request headers into the Request.Headers dictionary. You can use this just like any other dictionary. Here’s an example of using TryGetValue() to check if a request header exists and get its value: Note: To just check if a header … Read more

ASP.NET Core – Create a custom model validation attribute

There are many built-in model validation attributes available – such as [Required] and [Range] – which you can use to handle most validation scenarios. When these aren’t sufficient, you can create a custom validation attribute with your own validation logic. I’ll show an example of how to do that. 1 – Subclass ValidationAttribute and implement … Read more

ASP.NET Core – The request matched multiple endpoints

Problem When you send a request to an endpoint, you get the following error response: Note: If you’re using Swagger, you may see this in the UI as a generic error: “Failed to load API definition … response status is 500.” If you look in the ASP.NET Core Web Server output in Visual Studio, you … Read more

ASP.NET Core – API model validation attributes

It’s always a good idea to validate data coming into your web API. There are two steps you can do to guard against invalid data: Here’s an example of using model validation attributes: When a request comes in, the framework does two things: Let’s say you send a request with invalid data (boxOfficeMillions is outside … Read more

Redirect a request in ASP.NET Core

Redirecting a request means returning a response with redirect status code (3xx) and a redirect URL in the Location header. The client uses this info to follow the redirect (which means making a request to the redirect URL). You can redirect by using a helper method (from ControllerBase) or returning a RedirectResult. I’ll show several … Read more

ASP.NET Core – How to return a 500 response

The simplest way to return a 500 response is to use the Problem() helper method, like this: This method returns an ObjectResult with status code 500 and a generic error message, which gets serialized to JSON and returned in the response body. The response looks like this: The ControllerBase class has many helper methods like … Read more

ASP.NET Core – Getting query string values

The ASP.NET Core framework automatically parses query strings (i.e. ?name=Dune&year=2021) into HttpContext.Request.Query and maps the query string values to parameters in the action method (if you’ve added them). You can get the mapped query string values by adding action parameters, like this: Or you can use HttpContext.Request.Query directly (which is useful in many scenarios): This … Read more

ASP.NET Core – How to unit test an action filter

To unit test an action filter, you have to pass in an action filter context object (which requires a lot of setup). Action filter methods are void, so you have to verify the behavior by inspecting the context object (or dependencies, like a logger, if you are injecting those). Here’s an example of doing the … Read more

Add a custom action filter in ASP.NET Core

Action filters allow you to look at requests right before they are routed to an action method (and responses right after they are returned from the action method). The simplest way to add your own action filter in ASP.NET Core is to subclass ActionFilterAttribute and then override the appropriate methods depending on if you want … Read more

ASP.NET Core – Get posted form data in an API Controller

To get posted form data in an API Controller (using the [ApiController] attribute) in ASP.NET Core, use parameters with the [FromForm] attribute. Now send a request with form data to this endpoint to see it work. The request would look like this: The form data is a string of key-value pairs (ex: location=United+States). The framework … Read more

Logging to the database with ASP.NET Core

I was reading about logging in ASP.NET when I came across this statement about logging to the database: When logging to SQL Server, don’t do so directly. Instead, add log messages to an in-memory queue and have a background worker dequeue and insert data to SQL Server. Paraphrased from Microsoft – No asynchronous logger methods … Read more