Asp.net mvc 如何创建绑定int数组的模型绑定器?

Asp.net mvc 如何创建绑定int数组的模型绑定器?,asp.net-mvc,asp.net-web-api,model-binding,Asp.net Mvc,Asp.net Web Api,Model Binding,我正在我的ASP.NET MVC web API项目中创建一个GET端点,其目的是在URL中获取一个整数数组,如下所示: api.mything.com/stuff/2,3,4,5 public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType) { if (modelType == typeof(int[])) { return new IntArrayModelBi

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

api.mything.com/stuff/2,3,4,5
public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
  if (modelType == typeof(int[]))
  {
    return new IntArrayModelBinder();
  }

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

public string Get(int[] ids)
默认情况下,模型绑定不起作用-
ids
仅为null

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

但我无法触发模型绑定器。我创建了一个模型绑定器提供程序,如下所示:

api.mything.com/stuff/2,3,4,5
public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
  if (modelType == typeof(int[]))
  {
    return new IntArrayModelBinder();
  }

  return null;
}
它已经连接好了,所以我可以看到它在启动时执行,但我的ids参数仍然顽固地保持为空


我需要做什么?

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

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