Minimal APIs are the recommended approach for building fast HTTP APIs with ASP.NET Core. They allow you to build fully functioning REST endpoints with minimal code and configuration. You don't need a controller but can just declare your API using a fluent API approach:
This makes it very convenient to build your APIs. However you need to be aware that a lot of magic is going behind the scenes when using this approach. And this magic can bite you in the foot.
Exactly what happened to me while building an autonomous agent invoked through a web hook.
The code
In my application I created the following API endpoint using the minimal API approach:
The minimal API injects an AzureDevOpsWebhookParser that looks like this:
Nothing special…
The problem
The problem was when I called this endpoint, it failed with the following error message:
InvalidOperationException: TryParse method found on AzureDevOpsWebhookParser with incorrect format. Must be a static method with format...
To understand what is going wrong, you need to know how the model binding conventions work in ASP.NET Core Minimal APIs. If a parameter type has a public static TryParse method with one of the following signatures, the parameter will be bound using TryParse.
As our object doesn't implement such a method, you would think that it wouldn't be a problem. However, starting from .NET 6, a breaking change was introduced that validated the signature of any TryParse method found and throws an InvalidOperationException if it doesn’t match.
The solution
I looked at multiple ways to fix the problem. In the end I landed on a simple solution and just renamed the method to TryParsePayLoad so that the model binding conventions don’t apply.
Remark: While researching a possible solution I discovered the [AsParameters] attribute as a way to group some parameters into one object. But more details in my blog post tomorrow.
More information
Tutorial: Create a Minimal API with ASP.NET Core | Microsoft Learn
APIs overview | Microsoft Learn
Breaking change: TryParse and BindAsync methods are validated | Microsoft Learn