Bra*_*ton 5 asp.net-mvc asp.net-mvc-4 asp.net-web-api
所以似乎有几个人(比如这里和这里)在ApiControllers上遇到了MVC4模型绑定的问题,但是他们似乎都没有解决我看到的问题.
我真正想做的就是更改整数列表的数组绑定行为.所以说我有这样的请求类型:
public class MyRequestModel
{
public List<long> ListOfIntegers { get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
和这样的API GET方法:
public ResultsResponseModel Get(MyRequestModel request)
{
// use request.ListOfIntegers meaningfully
...
return response;
}
Run Code Online (Sandbox Code Playgroud)
我基本上希望能够说出/api/results/?listOfIntegers=1+2+3+4+5并拥有该List<long>财产的决心.
我尝试过我常用的模型绑定技巧,但与MVC4中的大多数Web API一样,它似乎有一个完全独立的模型绑定路径.
我得到的最远的是使用System.Web.Http.ModelBinding.ModelBinder属性MyRequestModel,并创建一个"实现"的模型绑定器System.Web.Http.ModelBinding.IModelBinder.这始终产生一个对象引用异常,堆栈跟踪从不触及我的代码.
有谁打过这个?有关于接下来要尝试什么的想法?
更新:这是我在自定义中捕获的堆栈跟踪ExceptionFilterAttribute:
Object reference not set to an instance of an object.
at System.Web.Http.ModelBinding.DefaultActionValueBinder.BindParameterValue(HttpActionContext actionContext, HttpParameterBinding parameterBinding)
at System.Web.Http.ModelBinding.DefaultActionValueBinder.<>c__DisplayClass1.BindValuesAsync>b__0(RequestContentReadKind contentReadKind)
at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass38.<ToAsyncVoidTask>b__37()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
Run Code Online (Sandbox Code Playgroud)
如果您正在谈论 ApiControllers,那么您正在尝试在 Web API 和 MVC 中进行模型绑定 这是一个示例模型绑定器
public class MyRequestModelBinderProvider : ModelBinderProvider
{
MyRequestModelBinder binder = new MyRequestModelBinder();
public IdeaModelBinderProvider()
{
}
public override IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(MyRequestModel))
{
return binder;
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
这是注册自定义模型绑定程序提供程序的示例
IEnumerable<object> modelBinderProviderServices = GlobalConfiguration.Configuration.ServiceResolver.GetServices(typeof(ModelBinderProvider));
List<Object> services = new List<object>(modelBinderProviderServices);
services.Add(new MyRequestModelBinderProvider());
GlobalConfiguration.Configuration.ServiceResolver.SetServices(typeof(ModelBinderProvider), services.ToArray());
Run Code Online (Sandbox Code Playgroud)
现在,在自定义模型绑定器中,您可以使用上下文来访问查询字符串值
public class MyRequestModelBinder : IModelBinder
{
public MyRequestModelBinder()
{
}
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
MyRequestModel yourModel;
//use contexts to access query string values
//create / update your model properties
bindingContext.Model = yourModel;
//return true || false if binding is successful
}
Run Code Online (Sandbox Code Playgroud)
确保您使用的是 WebAPI 而不是 MVC 的类和接口。有些名称相同,但命名空间和 dll 不同
| 归档时间: |
|
| 查看次数: |
5297 次 |
| 最近记录: |