Microsoft’s official documentation on adding custom model binding providers to convert between (typically) a string and a custom type for complex model binding in ASP.NET Core as of .NET Core 3.1 goes something like this:
- Create an
IModelBinder
for your class and use[ModelBinder(BinderType = typeof(MyModelEntityBinder)]
to decorate each and every binding site, e.g.
public async Task<IActionResult> OnPost([ModelBinder(BinderType = typeof(MyModelEntityBinder)]) MyModel model)
, which provides the runtime with the type information it needs to instantiate the model binding provider and convert the input to a model. - Optionally create an
IModelBinderProvider
class and register it with the ASP.NET Core host to provide the type information ahead-of-time (once and for all), so that you can instead use the barebones and much shorter decoration at each model binding site instead:
public async Task<IActionResult> OnPost([ModelBinder] MyModel model)
The latter is significantly easier on the eyes and far less error prone… but where does the type registration take place? Per the linked documentation, the recommendation is the following in Startup.cs
: