如何使用`BindModel(HttpActionContext actionContext ...`签名?)创建自定义模型绑定器?

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接口:

  1. System.Web.Mvc.IModelBinder 这与以前的版本相同,并没有改变
  2. System.Web.Http.ModelBinding.IModelBinder它由Web API和ApiController使用.所以基本上在这个方法中你必须设置actionContext.ActionArguments相应的值.您不再返回模型实例.

  • 还必须注册自定义模型绑定器.ASP.Net Web API与MVC3的方式不同.看看[这篇文章](http://forums.asp.net/t/1773706.aspx/1),看看如何在MVC4 Beta中做到这一点.答案的底部很难弄清楚,但请注意你使用`GlobalConfiguration.Configuration.ServiceResolver.GetServices ...在`global.asax.cs`中设置它. (3认同)

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)