我将如何创建绑定的int数组模型绑定? [英] How would I create a model binder to bind an int array?
问题描述
我要创建我的ASP.NET MVC的Web API项目的GET端点其目的是采取一个整数数组在这样的网址:
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
这网址是由需要一个 INT []
参数的操作服:
This URL is served by an action that takes an int[]
parameter:
public string Get(int[] ids)
默认情况下,模型绑定不起作用 - IDS
只是空
所以,我创建了从逗号分隔的列表创建 INT []
模型粘合剂。很简单。
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;
}
它连接起来,所以我可以看到它执行在启动时,但仍然我的id参数仍然固执地空。
It's wired up so I can see it execute on startup but still my ids parameter remains stubbornly null.
我需要做什么呢?
推荐答案
以下是实现您的方案的一种方式:
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;
}
}
}
这篇关于我将如何创建绑定的int数组模型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!