Specifying the Problem Details and Controling XML Serialization

Learn about specifying problem details, simulating a custom bad request handling, and controlling XML serialization.

A feature added in ASP.NET Core 2.1 and later implements a web standard for specifying problem details. In Web API controllers decorated with [ApiController] in a project where compatibility with ASP.NET Core 2.2 or later is enabled, action methods that return IActionResult and return a client error status code, 4xx, which will automatically include a serialized instance of the ProblemDetails class in the response body. If we want to take control, we can create a ProblemDetails instance ourselves and include additional information.

Simulating bad request

Let’s simulate a bad request that needs custom data returned to the client:

Step 1: At the top of the implementation of the Delete action method, add statements to check if the id matches the literal string value “bad”, and if so, then return a custom problem details object, as shown in the following code:

Get hands-on with 1400+ tech skills courses.