asp.net-mvc – 如何在MVC4中调用自定义模型绑定器?
所以似乎有几个人(比如
here和
here)遇到了ApiControllers的MVC4模型绑定问题,但是他们似乎都没有解决我看到的问题.
我真正想做的就是更改整数列表的数组绑定行为.所以说我有这样的请求类型: public class MyRequestModel { public List<long> ListOfIntegers { get; set; } ... } 和这样的API GET方法: public ResultsResponseModel Get(MyRequestModel request) { // use request.ListOfIntegers meaningfully ... return response; } 我基本上希望能够说/ api / results /?listOfIntegers = 1 2 3 4 5并将其解析为List< long>属性. 我尝试过我常用的模型绑定技巧,但与MVC4中的大多数Web API一样,它似乎有一个完全独立的模型绑定路径. 我得到的最远的是在MyRequestModel上使用System.Web.Http.ModelBinding.ModelBinder属性,并创建一个“实现”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) 解决方法
如果您正在谈论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; } } 以下是注册自定义模型绑定程序提供程序的示例 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()); 现在,在您的自定义模型绑定器中,您可以使用上下文来访问查询字符串值 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 } 确保您使用WebAPI的类和接口而不是MVC.一些名称是相同的,但不同的名称空间和dll (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – InvalidOperationException:没有数据时读取的尝
- asp.net-mvc – 如何使用razor语法转换为对象
- asp.net-mvc – 如何在视图中的脚本部分中包含脚本包
- 管理页面来管理asp.net会员提供商和角色管理
- asp.net-mvc-3 – 在同一父视图上多次使用一个部分视图
- asp.net-mvc – 在ASP.NET MVC 3中使用WebGrid显示原始HTML
- asp.net – 分析器错误消息:无法生成代码.抛出了类型’Sys
- asp.net – 渗透测试人员说.ASPXAUTH cookie是不安全的并且
- ASP.NET 5中的子域路由
- asp.net – 验证摘要问题