【发布时间】:2014-08-19 15:20:07
【问题描述】:
我有以下几点:
- 请求网址:'endpoint/1,2,3?q=foo'
- 请求绑定的动作: 公共对象 Bar([ModelBinder] List ids, [FromUri] string q)
我想将“1,2,3”片段映射到“ids”参数,所以我根据this link创建了一个ModelBinderProvider,它应该调用正确的模型绑定器。
public class MyModelBinderProvider: ModelBinderProvider
{
public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
IModelBinder modelBinder = null;
if (modelType.IsGenericType && (modelType.GetGenericTypeDefinition() == typeof(List<>)))
{
modelBinder = new ListModelBinder();
}
return modelBinder;
}
}
我像这样在 Global.asax 中注册了提供程序:
GlobalConfiguration.Configuration.Services.Insert(typeof(ModelBinderProvider), 0, new MyModelBinderProvider());
原因:我创建此提供程序是因为我希望,无论 T 是什么('1,2,3' 或 '一、二、三'),绑定都能正常工作。
问题: 假设 T 是 'int';每次发送请求时,'modelType' 参数始终是 'int' 而不是我所期望的 - 'List',因此请求没有得到正确处理。
奇怪的事情:做这样的事情是可行的,但 T 是专门的,因此不是我想要的:
var simpleProvider = new SimpleModelBinderProvider(typeof(List<int>), new ListModelBinder());
GlobalConfiguration.Configuration.Services.Insert(typeof(ModelBinderProvider), 0, simpleProvider);
我看不到我做错了什么,为什么'modelType'参数不是预期值?
【问题讨论】:
-
请详细说明您为什么要这样做?您认为这很有用的实际情况是什么?因此,这似乎是对可能具有完全不同 URI 的更复杂解决方案的一种破解。
标签: asp.net asp.net-mvc asp.net-web-api asp.net-mvc-5 asp.net-web-api2