Graham Clark
Graham Clark

Reputation: 12966

How to do custom model binding for Web Api in a .NET Framework web application?

I'm starting to convert a legacy .NET Framework ASP.NET API (which does not use the WebApi framework) into a .NET Core WebApi project. Due to dependencies, as an intermediate step I'm just swapping out the current API framework for WebApi, keeping the project targetting the .NET Framework.

The current version of the API supports binding comma-separated values on the query string into array properties on the model; I want to continue to support this.

So I need some custom model binding. There are plenty of similar questions about this, but they all seem to use .NET Core, different versions of the WebApi framework, and omit the namespaces being used (e.g. ASP.NET Core 1 Web API Model Binding Array).

I'm using .NET Framework 4.7 and version 5.2.7 of various Microsoft.AspNet.WebApi packages. It seems like I need a class that implements IModelBinder, but this interface exists in at least 3 different namespaces.

Exactly what IModelBinder interface do I need to implement, and once I've implemented it, how do I tell the WebApi framework to use my binder for specific properties?

Upvotes: 1

Views: 2276

Answers (1)

Ruslan Gilmutdinov
Ruslan Gilmutdinov

Reputation: 1417

Since you are targeting Web API that is implemented via Microsoft.AspNet.WebApi packages, you need to use types from these packages. Specifically, you need IModelBinder from the namespace System.Web.Http.ModelBinding (it is defined in System.Web.Http.dll provided by Microsoft.AspNet.WebApi.Core package).

Please refer to THIS on how to implement and use binding comma-separated values on the query string.

Upvotes: 1

Related Questions