How to call Default Model Binding from custom binder in WebAPI?

安稳与你 提交于 2019-12-23 12:34:14

问题


I have a custom model binder in WebAPI that uses the following method from the `Sytem.Web.Http.ModelBinding' namespace which is the correct namespace for creating custom model binders for Web API:

public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{

}

I have a HTTP POST on a controller for which I want to use this custom model binder. The posted object contains roughly 100 fields. I want to change 2 of them. What I need is for default model binding to occur and then manipulate that model bound object for those 2 fields so that once the controller receives the object it is pristine.

The problem is I can't seem to model bind my object using the default binder from the model binding method above. In MVC there was the following:

base.BindModel(controllerContext, bindingContext);

This same approach does not work in WebAPI. Maybe I'm going about this wrong and there is another way to accomplish what I want so please suggest if a custom model binder is not the correct approach. What I'm trying to prevent doing is have to manipulate the posted object inside the controller. I could technically do that after it has been model bound, but I'm trying to do that earlier in the call stack so that the controller doesn't need to worry about the custom manipulation of those 2 fields.

How can I initiate default model binding against the bindingContext in my custom model binder so that I have a fully populated object where then I can just manipulate/massage the last 2 fields I need before returning?


回答1:


In WebApi the 'default' model binder is CompositeModelBinder which wraps all registered model binders. If you want to re-use it's functionality you could do something like:

public class MyModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(MyModel)) return false;

        //this is the default webapi model binder provider
        var provider = new CompositeModelBinderProvider(actionContext.ControllerContext.Configuration.Services.GetModelBinderProviders());
        //the default webapi model binder
        var binder = provider.GetBinder(actionContext.ControllerContext.Configuration, typeof(MyModel));

        //let the default binder do it's thing
        var result = binder.BindModel(actionContext, bindingContext);
        if (result == false) return false;

        //TODO: continue with your own binding logic....
    }
}


来源:https://stackoverflow.com/questions/36504824/how-to-call-default-model-binding-from-custom-binder-in-webapi

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