【发布时间】:2014-11-21 00:58:56
【问题描述】:
这个问题把我逼疯了。
我有一个使用自定义 ModelBinder 获取 ID 数组的 get 方法(我可以调用 http://xckvjl.com/api/results/1,23,34,)
我想介绍 Gets on action。 (这样我就可以打电话给http://alskjdfasl.com/api/results/latest)
我有以下 web api 路由。
config.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute("ApiWithAction", "{controller}/{action}");
我已经尝试过(请注意这里我使用的是我的自定义模型绑定器)
config.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional }, new {id = @"\d+" });
您可以使用此示例重现此错误:
public class TestController: ApiController {
[HttpGet]
public virtual IHttpActionResult Get([ModelBinder(typeof(CommaDelimitedCollectionModelBinder))]IEnumerable<int> id = null )
{ }
[HttpGet]
public virtual IHttpActionResult Latest( )
{ }
}
public class CommaDelimitedCollectionModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext,
ModelBindingContext bindingContext)
{
var key = bindingContext.ModelName;
var val = bindingContext.ValueProvider.GetValue(key);
if (val == null)
{
return false;
}
var s = val.AttemptedValue;
if (s != null && s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Length > 0)
{
var array = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select( n=>Convert.ToInt32(n)).ToArray();
Type type = bindingContext.ModelType.GetGenericArguments().First();
var typeValue = Array.CreateInstance(type, array.Length);
array.CopyTo(typeValue, 0);
bindingContext.Model = array;
}
else
{
bindingContext.Model = new[] { s };
}
return true;
}
}
如果我写成:
[HttpGet]
[Route("Tests/latest")]
public virtual IHttpActionResult Latest( )
{ }
它有效。但是,我想要全局级路由。否则对于每一个动作,我都必须写相同的。
请指教。
【问题讨论】:
标签: c# .net asp.net-web-api asp.net-web-api-routing