Moh*_*ani 25 asp.net-mvc imodelbinder asp.net-mvc-4 asp.net-web-api
我需要知道如何IModelBinder在MVC 4中创建自定义并且它已被更改.
必须实施的新方法是:
bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 28
有2个IModelBinder接口:
System.Web.Mvc.IModelBinder 这与以前的版本相同,并没有改变System.Web.Http.ModelBinding.IModelBinder它由Web API和ApiController使用.所以基本上在这个方法中你必须设置actionContext.ActionArguments相应的值.您不再返回模型实例.Tod*_*odd 24
这个链接由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;
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,提供一个提供程序,它作为新活页夹的工厂,以及您将来可能添加的任何其他活页夹.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
最后,在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());
Run Code Online (Sandbox Code Playgroud)
现在,您可以将新类型作为参数添加到操作方法中.
public HttpResponseMessage<Contact> Get([ModelBinder(typeof(CustomModelBinderProvider))] User user)
Run Code Online (Sandbox Code Playgroud)
甚至
public HttpResponseMessage<Contact> Get(User user)
Run Code Online (Sandbox Code Playgroud)
小智 8
在没有ModelBinderProvider的情况下添加模型绑定器的一种简单方法是这样的:
GlobalConfiguration.Configuration.BindParameter(typeof(User), new CustomModelBinder());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14327 次 |
| 最近记录: |