问题
I am implementing custom model binder. I researched how to do it and found out that in case of WebApi I need to implement IModelBinder
interface.
My implementation looks like this:
public class ModelBaseBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if ((bindingContext.Model is MyModel))
{
//my code here
controller.InitModel(model);
return true;
}
return false;
}
}
I am just not sure if my implenentaton is complete. Do I need to call any default WebApi BindModel
in order my custom implementation work?
回答1:
I am uncertain of this implementation as I haven't tried it before. The mechanism with which I have applied to custom model binders is set the Model to an instance of my model class using the bindingContext.Model property.
ex). bindingContext.Model = new Foo();
To get the custom model binder to function in the configuration it is necessary to either use a ModelBinder attribute next to the action parameter, apply the model binder attribute to the model class, or create a parameter binding rule. Applying the model binder attribute to the action method parameter adds some flexibility into where the model binder is used and is a straightforward approach
public IHttpActionResult FooAction([ModelBinder(BinderType=typeof(mymodelbinder))]Foo myFoo) { }
来源:https://stackoverflow.com/questions/32274044/how-to-implement-webapi-custom-model-binder