【问题标题】:How would I create a model binder to bind an int array?我将如何创建一个模型绑定器来绑定一个 int 数组?
【发布时间】:2014-03-14 16:00:24
【问题描述】:

我正在我的 ASP.NET MVC Web API 项目中创建一个 GET 端点,该端点旨在在 URL 中获取一个整数数组,如下所示:

api.mything.com/stuff/2,3,4,5

此 URL 由采用 int[] 参数的操作提供:

public string Get(int[] ids)

默认情况下,模型绑定不起作用 - ids 只是 null。

所以我创建了一个模型绑定器,它从逗号分隔的列表中创建一个int[]。很简单。

但我无法触发模型绑定器。我创建了一个这样的模型绑定器提供程序:

public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
  if (modelType == typeof(int[]))
  {
    return new IntArrayModelBinder();
  }

  return null;
}

它已经连线,所以我可以看到它在启动时执行,但我的 ids 参数仍然顽固地为空。

我需要做什么?

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api model-binding


    【解决方案1】:

    以下是实现您的方案的一种方法:

    configuration.ParameterBindingRules.Insert(0, IntArrayParamBinding.GetCustomParameterBinding);
    ----------------------------------------------------------------------
    public class IntArrayParamBinding : HttpParameterBinding
    {
        private static Task completedTask = Task.FromResult(true);
    
        public IntArrayParamBinding(HttpParameterDescriptor desc)
            : base(desc)
        {
        }
    
        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            HttpRouteData routeData = (HttpRouteData)actionContext.Request.GetRouteData();
    
            // note: here 'id' is the route variable name in my route template.
            int[] values = routeData.Values["id"].ToString().Split(new char[] { ',' }).Select(i => Convert.ToInt32(i)).ToArray();
    
            SetValue(actionContext, values);
    
            return completedTask;
        }
    
        public static HttpParameterBinding GetCustomParameterBinding(HttpParameterDescriptor descriptor)
        {
            if (descriptor.ParameterType == typeof(int[]))
            {
                return new IntArrayParamBinding(descriptor);
            }
    
            // any other types, let the default parameter binding handle
            return null;
        }
    
        public override bool WillReadBody
        {
            get
            {
                return false;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多