I am having a lot of trouble getting custom model binding to work when posting x-www-form-urlencoded
data. I\'ve tried every way I can think of and nothing seems to
ModelBinder seem relatively better to use than MediaTypeFormatter. You do not need to register it globally.
I found another alternative to use model binder to bind complex object types in Web API. In model binder, I am reading request body as string and then using JSON.NET to deserialize it to required object type. It can be used to map array of complex object types as well.
I added a model binder as follows:
public class PollRequestModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var body = actionContext.Request.Content.ReadAsStringAsync().Result;
var pollRequest = JsonConvert.DeserializeObject(body);
bindingContext.Model = pollRequest;
return true;
}
}
And then I am using it in Web API controller as follows:
public async Task Post(Guid instanceId, [ModelBinder(typeof(PollRequestModelBinder))]PollRequest request)
{
// api implementation
}