atc*_*way 7 custom-model-binder asp.net-web-api asp.net-web-api2
我在 WebAPI 中有一个自定义模型绑定器,它使用来自“Sytem.Web.Http.ModelBinding”命名空间的以下方法,这是为 Web API 创建自定义模型绑定器的正确命名空间:
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
}
Run Code Online (Sandbox Code Playgroud)
我有一个HTTP POST控制器,我想使用这个自定义模型绑定器。发布的对象包含大约 100 个字段。我想换 2 个。我需要的是发生默认模型绑定,然后为这两个字段操作该模型绑定对象,以便一旦控制器接收到对象,它就是原始的。
问题是我似乎无法使用上述模型绑定方法中的默认绑定器对我的对象进行模型绑定。在MVC曾有如下:
base.BindModel(controllerContext, bindingContext);
同样的方法也没有在工作的WebAPI。也许我要解决这个错误,还有另一种方法可以完成我想要的,所以请建议自定义模型绑定器是否不是正确的方法。我试图阻止做的是必须在控制器内操作发布的对象。我可以在模型绑定后在技术上做到这一点,但我试图在调用堆栈的早期执行此操作,以便控制器无需担心这两个字段的自定义操作。
如何bindingContext在我的自定义模型绑定器中启动默认模型绑定,以便我有一个完全填充的对象,然后我可以在返回之前操作/按摩我需要的最后 2 个字段?
在 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....
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2159 次 |
| 最近记录: |