问题
I'm creating a GET endpoint in my ASP.NET MVC web API project which is intended to take a an integer array in the URL like this:
api.mything.com/stuff/2,3,4,5
This URL is served by an action that takes an int[]
parameter:
public string Get(int[] ids)
By default, the model binding doesn't work - ids
is just null.
So I created a model binder which creates an int[]
from a comma-delimited list. Easy.
But I can't get the model binder to trigger. I created a model binder provider like this:
public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
if (modelType == typeof(int[]))
{
return new IntArrayModelBinder();
}
return null;
}
It's wired up so I can see it execute on startup but still my ids parameter remains stubbornly null.
What do I need to do?
回答1:
Following is one way of achieving your scenario:
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;
}
}
}
来源:https://stackoverflow.com/questions/22410085/how-would-i-create-a-model-binder-to-bind-an-int-array