【问题标题】:C# Web.API Cannot add custom model binderC# Web.API 无法添加自定义模型绑定器
【发布时间】:2016-04-06 20:06:35
【问题描述】:

我的 API 控制器有一个 Put 方法

public class ScheduleExecutionsController : ApiController
{

    public ScheduleExecutionsResponse Put([ModelBinder(typeof(TestBinder))]ScheduleExecutionsRequest requestInfo)
    {
        ....
    }
}

我在项目中添加了一个 binder 类

public class TestBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        return new ScheduleExecutionsRequest();
    }
}

我设置了 2 个断点。第一个到控制器中 Put 方法的第一行,第二个到我的 TestBinder BindModel 对象的第一行。 使用 Fiddler 后,我发送 PUT 请求。

调试器总是在我的操作中停止,但永远不会在活页夹的 BindModel 方法中停止。似乎使用了默认活页夹。添加自定义项我错过了什么?

【问题讨论】:

标签: c# asp.net-web-api model-binding custom-model-binder


【解决方案1】:

您使用的是WebAPIMVC 版本的ModelBinderAttribute

MVC 和 WebAPI 的大部分基础设施——过滤器、绑定等——以两种形式存在(由于这两个库的历史)。您的 WebAPI 控制器和操作必须使用这些的 WebAPI 版本(命名空间 System.Web.Http 或其子命名空间)。

【讨论】:

  • 非常感谢。这是 IModelBinder 在 Binder calss 的命名空间错误的问题,而且模型绑定器属性应该看起来像这样 [System.Web.Http.ModelBinding.ModelBinder(typeof(TestBinder))]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-31
  • 2014-03-10
  • 2012-02-18
  • 2012-01-29
  • 2018-08-22
  • 1970-01-01
  • 2011-02-08
相关资源
最近更新 更多