While converting an existing ASP.NET MVC application to ASP.NET Core I noticed it was using a custom model binder. That made me wonder how I could achieve the same thing in ASP.NET Core.
In ASP.NET MVC a model binder had to implement the IModelBinder interface:
To use the model binder you had to let the ASP.NET MVC framework know the existence of the custom model binder. In the original codebase we were using Unity and we created a small extension method that allowed us to register the Modelbinder:
That extension method allowed us to write the following code:
Let’s find out how to achieve the same result in ASP.NET Core…
In ASP.NET Core you should also implement a IModelBinder interface, although the contract is different(and async):
To use this custom model binder you can either create a custom ModelBinderProvider or use the ModelBinder attribute:
More information: Custom Model Binding in ASP.NET Core