How to implement WebApi custom model binder

旧城冷巷雨未停 提交于 2019-12-13 19:41:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!