[HttpPut]
[ActionName("Index")]
public ActionResult Change()
{
return View();
}
MVC のアクション メソッド セレクターでは、同じ名前のメソッドに対して最大で 2 つのアクション メソッドのオーバーロードのみを許可します。URL パスに {controller}/{id} のみを使用したいというお気持ちは理解できますが、間違った方法で行っている可能性があります。
コントローラーのアクション メソッドが 2 つしかない場合 (GET 用に 1 つ、PUT 用に 1 つ)、上記のように、または次のように、両方のアクションに Index という名前を付けることができます。
[HttpPut]
public ActionResult Index()
{
return View();
}
コントローラーに 2 つ以上のメソッドがある場合は、他のアクション用に新しいカスタム ルートを作成するだけです。コントローラーは次のようになります。
[HttpPut]
public ActionResult Put()
{
return View();
}
[HttpPost]
public ActionResult Post()
{
return View();
}
[HttpGet]
public ActionResult Get()
{
return View();
}
[HttpDelete]
public ActionResult Delete()
{
return View();
}
... global.asax が次のようになっている場合:
routes.MapRoute(null,
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "Get", id = UrlParameter.Optional },
new { httpMethod = new HttpMethodConstraint("GET") }
);
routes.MapRoute(null,
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "Put", id = UrlParameter.Optional },
new { httpMethod = new HttpMethodConstraint("PUT") }
);
routes.MapRoute(null,
"{controller}", // URL with parameters
new { controller = "Home", action = "Post", id = UrlParameter.Optional },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(null,
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "Delete", id = UrlParameter.Optional },
new { httpMethod = new HttpMethodConstraint("DELETE") }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
... これらの新しい 4 つのルートはすべて、POST を除いて同じ URL パターンを持っています (コレクションに POST する必要があるため、特定の ID に PUT する必要があるため)。ただし、異なる HttpMethodConstraints は、MVC ルーティングに対して、httpMethod が対応する場合にのみルートに一致するように指示します。したがって、誰かが DELETE を /MyItems/6 に送信すると、MVC は最初の 3 つのルートには一致しませんが、4 番目のルートには一致します。同様に、誰かが PUT を /MyItems/13 に送信した場合、MVC は最初の 2 つのルートには一致しませんが、3 番目のルートには一致します。
MVC がルートと一致すると、そのルート定義のデフォルト アクションが使用されます。したがって、誰かが DELETE を送信すると、コントローラーの Delete メソッドにマップされます。