魔王のサタンぶろぐ

.NET Framework4.6 And MVC5 で作るIModelBinder

CustomIModelBinderについて

まず初めに僕が今回CustomIModelBinderを作るに至った状況を参考に紹介します。

  1. JSONをPOSTするAPIを作成
  2. バインドするモデルのメンバにinterface,abstract(抽象クラス)を含めた
  3. バインドするメンバにValidate(Require等)を属性として付与

こんな状況になったわけです。

開発環境

  • .NETFramework4.6
  • MVC5
  • NewtonJson

今回はIModelBinderについて

MVC4か3でIModelBinderの形式が変わってて自分が参考にしていたものが使えなくなったということで今回はこの記事を書きました。

using System.Web.Http.ModelBinding; // 間違わないように

public class SampleBinder : IModelBinder{
 // インターフェース実装
 public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
  {
    // 内部処理
    SampleClass sample = new SampleClass();
    
    JsonConverter[] converters = { new SampleConverter() }; //ここは後日(Jsonのカスタムオプション)

    using(var reader = new StreamRender(actionContext.Request.Content.ReadAsStreamAsync().Result)) // Json読み取り
    {
      var str = render.ReadToEnd();
      string jsonStrring = str.Replace("\n","");  // お掃除
      sample = JsonConvert.DeserializeObject<SampleClass>(jsonString, new JsonSerializerSettings() { Converters = converters });
    }

    if(sample != null)
    {
    // 忘れちゃいけないの以下
    bindingContext.Model = sample // ここ重要
    return true;
    }
    else
    {
      return false;
    }
  }
}

でまぁ構造的にはCustiomIModelBinderができました。 今度はどうやって使うかですが、 バインドするModelClassの上に属性として渡してあげましょう

namespace MVC.Models.Sample{
 [ModelBinder(typeof(SampleBinder)]
 public class SampleClass{
  // メンバー定義
 }
}

これで完璧です。

結局

“バインドするClass.jsonを作り直して"で解決するんですけどね?(笑)

ばいん