So none of the existing questions answer this.
I have implemented a custom model binder for web api 2 as below
public class AModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
return modelType == typeof(A) ? new AdAccountModelBinder() : null;
}
}
public class AModelBinder : DefaultModelBinder
{
private readonly string _typeNameKey;
public AModelBinder(string typeNameKey = null)
{
_typeNameKey = typeNameKey ?? "type";
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var providerResult = bindingContext.ValueProvider.GetValue(_typeNameKey);
if (providerResult != null)
{
var modelTypeName = providerResult.AttemptedValue;
SomeEnum type;
if (!Enum.TryParse(modelTypeName, out type))
{
throw new InvalidOperationException("Bad Type. Does not inherit from AdAccount");
}
Type modelType;
switch (type)
{
case SomeEnum.TypeB:
modelType = typeof (B);
break;
default:
throw new InvalidOperationException("Bad type.");
}
var metaData =
ModelMetadataProviders.Current
.GetMetadataForType(null, modelType);
bindingContext.ModelMetadata = metaData;
}
// Fall back to default model binding behavior
return base.BindModel(controllerContext, bindingContext);
}
Models are defined as below -
Public class A {}
Public Class B : A {}
Web Api Action as below -
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/a")]
[System.Web.Http.Authorize]
public async Task<HttpResponseMessage> Add([ModelBinder(typeof(AModelBinderProvider))]Models.A a)
{}
Registered my provider as a gentleman in Application_Start -
var provider = new AdAccountModelBinderProvider();
ModelBinderProviders.BinderProviders.Add(provider);
Still my custom Binder refuses to fire up.
I am lost. What am I missing?