オブジェクトごとに追加のコーディングをほとんど必要とせずに、任意のオブジェクトを処理する汎用 JSON API を作成しています。以下は、他のすべてのコントローラー (EmployeeController、ProductController など) が継承する BaseController です。
public partial class BaseController<T> : Controller where T : ModelBase<T>, new()
{
[RestHttpVerbFilter]
public ActionResult Index (long? Id, string Property, long? PropertyId, T Model, string Format, string HttpVerb)
{
switch (HttpVerb)
{
case "GET":
return Json(Get(Id.Value, Property, PropertyId), JsonRequestBehavior.AllowGet);
case "POST":
return Json(Post(Id, Property, PropertyId, Model));
case "PUT":
return Json(Put(Id.Value, Property, PropertyId, Model));
case "DELETE":
return Json(Delete(Id, Property, PropertyId));
}
return Json(new { error = "Unknown HTTP verb" });
}
internal object Post (long? Id, string Property, long? PropertyId, T Model)
{
if (!Id.HasValue && string.IsNullOrEmpty(Property) && !PropertyId.HasValue && Repository.Add(Model))
{
return Get(Model.ID);
}
return new { error = "Unable to save new " + typeof(T).Name };
}
internal object Put (long? Id, string Property, long? PropertyId, T Model)
{
if (Id.HasValue)
{
Model.ID = Id.Value;
if (string.IsNullOrEmpty(Property) && !PropertyId.HasValue && Repository.Update(Model))
{
return Get(Id.Value);
}
}
return new { error = "Unable to update " + typeof(T).Name };
}
無関係なコード (Get、Delete) を削除しました。GET
現在、43 の Id で指定された Venue ですべてのイベントを返すようなリクエストを行うことができるようにセットアップしました。また、新しい Venue を作成することhttp://example.com/API/Venue/43/Events
もできます。その会場の新しいイベントを作成できるようにしたいと考えています。POST
http://example.com/API/Venue
POST
http://example.com/API/Venue/43/Events
Index
アクションのパラメーターでは、現在、Model
オブジェクトは投稿されたときに会場を取得します。アクションにPOST
Event オブジェクトを渡すと、Model
パラメーターは引き続きそれを取得します。以下に置き換えてみましT Model
たが、次の問題が発生しました。
object Model
POST
、次に、編集先のURL に基づいてキャストします。これにより、System.InvalidCastException
dynamic Model
、次にそれをキャストし(T)Model
ます。これはまた、System.InvalidCastException
dynamic Model
、次にそれをキャストしModel as T
ます。Model
その場合はnull
、キャストが失敗したことを意味しますIModelBase Model
、モデルバインダーがインスタンス化しようとするため機能しないインターフェース
dynamic
私は aがうまくいったと思っていたでしょうが、 InvalidCastException
. 上記のコードは、コントローラーのオブジェクト ( POST
ing a Venue to http://example.com/API/Venue
) に対して機能します。