如何实现的WebAPI自定义模型粘合剂 [英] How to implement WebApi custom model binder
问题描述
我实现自定义模型粘合剂。我研究了如何做到这一点,并发现,在的WebAPI的情况下,我需要实施 IModelBinder
接口。
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.
我的实现是这样的:
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;
}
}
我只是不知道如果我implenentaton完成。我是否需要调用任何默认的WebAPI BindModel
为了我的自定义执行工作?
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?
推荐答案
我不清楚,因为我还没有尝试过这种实现的。与我已应用到自定义模型粘合剂的机制设定的模型使用bindingContext.Model物业我的模型类的一个实例。
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.
恩)。 bindingContext.Model =新的Foo();
ex). bindingContext.Model = new Foo();
要获得自定义模型粘结剂要么使用ModelBinder的属性旁边的操作参数,模型绑定属性应用到模型类,或创建一个参数绑定规则,必须配置的功能。应用模型绑定属性的操作方法参数增加了一些灵活性,使用模型绑定的地方,是一个直接的方法
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) { }
这篇关于如何实现的WebAPI自定义模型粘合剂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!