バックグラウンド
シンプルなブログ アプリ用に、REST に似た API サービス コントローラーを作成しました。基本的な CRUD を処理するために 2 つのルートを使用します。
// Actions should handle: GET, POST, PUT, DELETE
routes.MapRoute("Api-SingleThing", "thing/{id}",
new { controller = "ThingService", action = "SingleThing" });
// Action should handle: GET
routes.MapRoute("Api-AllThings", "things",
new { controller = "ThingService", action = "AllThings" });
一致するコントローラー コードは次のようになります。
[HttpGet]
public ActionResult AllThings() {}
[HttpGet]
[ActionName("SingleThing")]
public ActionResult Get(string id) {}
[HttpPost]
[ActionName("SingleThing")]
public JsonResult Create(Thing thing) {}
[HttpPut]
[ActionName("SingleThing")]
public ActionResult Update(Thing thing) {}
[HttpDelete]
[ActionName("SingleThing")]
public ActionResult Delete(int id) {}
この[ActionName()]
属性は、ルートの制約を回避するために使用されるため、ルートがトリガーされると、HTTP 動詞に関係なく、コントローラーで常に「SingleThing」アクションが呼び出されます。[HttpVerb]
これにより、名前を共有するコントローラー アクション メソッドが、属性に基づいてリクエストを処理するユーザーを決定できます。
私のブログ アプリでは、これは魅力のように機能しますが、ルート パラメーター (別名スラッグ) が onおよびrequests{id}
であっても常に存在するためです。POST
PUT
上に示したこの新しい API では、POST
andPUT
アクションは最初のルートをトリガーせず (例:{id}
値なし)、2 番目のルートをトリガーすると、動詞のためにそれらを処理するメソッドがありません。
質問
この REST-ful URL アーキテクチャと動詞処理を維持し、POST および PUT アクションを確実にトリガーするための最良の方法は何ですか?