【问题标题】:How to call Default Model Binding from custom binder in WebAPI?如何从 WebAPI 中的自定义绑定器调用默认模型绑定?
【发布时间】:2023-03-30 14:05:01
【问题描述】:

我在 WebAPI 中有一个自定义模型绑定器,它使用来自 `Sytem.Web.Http.ModelBinding' 命名空间的以下方法,为 Web API 创建自定义模型绑定器的正确命名空间:

public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{

}

我在一个控制器上有一个HTTP POST,我想使用这个自定义模型绑定器。发布的对象包含大约 100 个字段。我想改变其中的2个。我需要的是发生默认模型绑定,然后为这两个字段操作该模型绑定对象,以便一旦控制器接收到对象,它就是原始对象。

问题是我似乎无法使用上述模型绑定方法中的默认绑定器对我的对象进行模型绑定。在MVC 中有以下内容:

base.BindModel(controllerContext, bindingContext);

同样的方法在 WebAPI 中起作用。也许我正在解决这个错误,还有另一种方法可以完成我想要的,所以如果自定义模型绑定器不是正确的方法,请提出建议。我试图阻止的是必须在控制器内操作发布的对象。我可以技术上在绑定模型之后这样做,但我试图在调用堆栈的早期这样做,这样控制器就不需要担心这两个字段的自定义操作.

如何在我的自定义模型绑定器中针对 bindingContext 启动默认模型绑定,以便我拥有一个完全填充的对象,然后我可以在返回之前操作/按摩我需要的最后 2 个字段?

【问题讨论】:

  • 我意识到这是几年后的事了,但我想知道您是否找到了解决方案?我现在面临同样的问题。 @atconway

标签: asp.net-web-api asp.net-web-api2 custom-model-binder


【解决方案1】:

在 WebApi 中,“默认”模型绑定器是 CompositeModelBinder,它包含所有已注册的模型绑定器。如果你想重用它的功能,你可以这样做:

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....
    }
}

【讨论】:

  • 我正试图弄清楚如何将现有的 MyModelBinder 排除在调用自身之外,因为它是 MyModel 的默认绑定器。
  • 您找到解决方案了吗?
  • 你@ntziolis 了吗?
猜你喜欢
  • 2018-08-22
  • 2012-04-24
  • 2022-12-16
  • 1970-01-01
  • 2022-01-01
  • 2018-10-13
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
相关资源
最近更新 更多