MVC 4 ModelBinder
我需要知道如何在MVC 4中创建自定义IModelBinder
并且它已被更改。MVC 4 ModelBinder
必须被实施的新的方法是:
bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
有2个IModelBinder接口:
-
System.Web.Mvc.IModelBinder
这是相同的,如以前的版本和未改变 - 它由Web API和ApiController使用,它由
System.Web.Http.ModelBinding.IModelBinder
组成。所以基本上在这个方法中,你必须将actionContext.ActionArguments
设置为相应的值。您不再返回模型实例。
This link由Steve提供,提供了一个完整的答案。我将它添加到这里供参考。信用在asp.net论坛上发布到dravva。
首先,创建一个从IModelBinder
派生的类。正如Darin所说,一定要使用System.Web.Http.ModelBinding
命名空间,而不是熟悉的MVC等价物。
public class CustomModelBinder : IModelBinder
{
public CustomModelBinder()
{
//Console.WriteLine("In CustomModelBinder ctr");
}
public bool BindModel(
HttpActionContext actionContext,
ModelBindingContext bindingContext)
{
//Console.WriteLine("In BindModel");
bindingContext.Model = new User() { Id = 2, Name = "foo" };
return true;
}
}
接下来,提供一个供应商,它充当一个工厂为新的粘合剂,和任何其他粘合剂则可能在未来加入。
public class CustomModelBinderProvider : ModelBinderProvider
{
CustomModelBinder cmb = new CustomModelBinder();
public CustomModelBinderProvider()
{
//Console.WriteLine("In CustomModelBinderProvider ctr");
}
public override IModelBinder GetBinder(
HttpActionContext actionContext,
ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(User))
{
return cmb;
}
return null;
}
}
最后,在Global.asax.cs中包含以下内容(例如,Application_Start)。
var configuration = GlobalConfiguration.Configuration;
IEnumerable<object> modelBinderProviderServices = configuration.ServiceResolver.GetServices(typeof(ModelBinderProvider));
List<Object> services = new List<object>(modelBinderProviderServices);
services.Add(new CustomModelBinderProvider());
configuration.ServiceResolver.SetServices(typeof(ModelBinderProvider), services.ToArray());
现在,您可以将新类型作为参数拖动到您的操作方法中。
public HttpResponseMessage<Contact> Get([ModelBinder(typeof(CustomModelBinderProvider))] User user)
甚至
public HttpResponseMessage<Contact> Get(User user)
我相信,只要您明确使用[ModelBinder (typeof(CustomModelBinderProvider))],你不需要ModelBinderProvider。 – 2013-03-18 09:15:07
赛后RC更新托德的职位:
将您的模型绑定提供商已被简化:
var configuration = GlobalConfiguration.Configuration;
configuration.Services.Add(typeof(ModelBinderProvider), new YourModelBinderProvider());
这对我有效。有没有办法在全球范围内做到这一点,即设置默认模型联编程序? – 2012-09-25 19:15:39
一个更简单的方式来增加没有ModelBinderProvider的modelbinder是这样的:
GlobalConfiguration.Configuration.BindParameter(typeof(User), new CustomModelBinder());
这工作完美!无论出于何种原因,我无法在此页面上获得任何其他示例以使用MVC4。 ModelBinderProvider的接口似乎已经改变。但是移除ModelBinderProvider并将此代码添加到Application_Start效果很好! – 2013-04-26 14:48:54
Yesss,谢谢Darin。 – 2012-03-28 15:17:15
还需要注册自定义模型联编程序。 ASP.Net Web API没有与MVC3相同的方式。看看[这篇文章](http://forums.asp.net/t/1773706.aspx/1)看看如何在MVC4 Beta中做到这一点。答案的底部很难弄清楚,但请注意,您可以在'global.asax.cs'中用'GlobalConfiguration.Configuration.ServiceResolver.GetServices ...'设置它# – Steve 2012-03-29 04:27:27