为什么我不能为List <int>?</int>注册自定义模型绑定器

时间:2013-06-26 16:19:57

标签: asp.net-mvc asp.net-mvc-4 model-binding

我有一个看起来像

的动作
public ActionResult GetUsers(List<int> userIds) {//do stuff}

userIds列表可能会很长,所以我想使用Json.Net对其进行反序列化。为此,我创建了一个IModelBinder实现,该实现适用于其他对象,但从不为List调用。 IModelBind看起来像这样

public class JsonBinder : System.Web.Mvc.IModelBinder
{
  public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
  { //Do model binding stuff using Json.Net }
} 

我用这一行注册了这个模型绑定器

ModelBinders.Binders.Add(typeof(List<int>), new JsonBinder());

然而JsonBinder从未被调用过。为什么是这样?我应该使用ValueProvider吗?

2 个答案:

答案 0 :(得分:1)

在global.asax中添加以下事件(或将代码添加到现有的Application_BeginRequest处理程序):

protected void Application_BeginRequest()
{
    foreach (var type in ModelBinders.Binders.Keys)
    {
        System.Diagnostics.Trace.WriteLine(
                              String.Format("Binder for '{0}': '{1}'", 
                                             type.ToString(), 
                                             ModelBinders.Binders[type].ToString()));
    }

}

然后,您可以在VS输出窗口中检查当前注册的绑定器。你可以看到这样的东西:

Binder for 'System.Web.HttpPostedFileBase': 'System.Web.Mvc.HttpPostedFileBaseModelBinder'
Binder for 'System.Byte[]': 'System.Web.Mvc.ByteArrayModelBinder'
Binder for 'System.Data.Linq.Binary': 'System.Web.Mvc.LinqBinaryModelBinder'
Binder for 'System.Threading.CancellationToken': 'System.Web.Mvc.CancellationTokenModelBinder'

您还可以检查是否有任何ModelBinderProvider可以选择活页夹提供程序,因为选择使用哪个模型活页夹的顺序如下:

  1. 动作参数的属性。请参阅ControllerActionInvoker class

  2. 的GetParameterValue方法
  3. Binder从IModelBinderProvider返回。请参阅ModelBinderDictionary class

  4. 中的GetBinder方法
  5. Binder全球注册在ModelBinders.Binders词典中。

  6. Binder在模型类型的[ModelBinder()]属性中定义。

  7. DefaultModelBinder。

  8. 使用类似的方法检查BeginRequest事件中的模型绑定程序提供程序:

    foreach (var binderprovider in ModelBinderProviders.BinderProviders)
    {
        System.Diagnostics.Trace.WriteLine(String.Format("Binder for '{0}'", binderprovider.ToString()));
    }
    

    此外,您可以尝试通过nuget添加Glimpse,因为其中一个选项卡提供了有关用于控制器操作中每个参数的模型绑定器的信息。

    希望这可以帮助您跟踪未使用模型装订器的原因。

答案 1 :(得分:0)

您是否尝试在操作方法中使用ModelBinder属性?

public ActionResult GetUsers([ModelBinder(typeof(JsonBinder))] List<int> userIds)

参考:https://msdn.microsoft.com/en-us/library/system.web.mvc.modelbinderattribute(v=vs.118).aspx