MVC 4でカスタムを作成する方法を知る必要がありIModelBinder
、それが変更されました。
実装する必要がある新しいメソッドは次のとおりです。
bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
MVC 4でカスタムを作成する方法を知る必要がありIModelBinder
、それが変更されました。
実装する必要がある新しいメソッドは次のとおりです。
bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
2つのIModelBinderインターフェースがあります。
System.Web.Mvc.IModelBinder
これは以前のバージョンと同じで、変更されていませんSystem.Web.Http.ModelBinding.IModelBinder
これは、WebAPIとApiControllerによって使用されます。したがって、基本的にこのメソッド内ではactionContext.ActionArguments
、を対応する値に設定する必要があります。モデルインスタンスを返すことはもうありません。スティーブによって提供されたこのリンクは、完全な答えを提供します。参考までにここに追加します。クレジットは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)
ModelBinderProviderなしでmodelbinderを追加するさらに簡単な方法は、次のとおりです。
GlobalConfiguration.Configuration.BindParameter(typeof(User), new CustomModelBinder());
Toddの投稿に対する投稿RCの更新:
モデルバインダープロバイダーの追加が簡素化されました。
var configuration = GlobalConfiguration.Configuration;
configuration.Services.Add(typeof(ModelBinderProvider), new YourModelBinderProvider());