このMapRouteを検討してください。
MapRoute(
"ResultFormat",
"{controller}/{action}/{id}.{resultFormat}",
new { controller = "Home", action = "Index", id = 0, resultFormat = "json" }
);
そしてそれはコントローラーメソッドです:
public ActionResult Index(Int32 id, String resultFormat)
{
var dc = new Models.DataContext();
var messages = from m in dc.Messages where m.MessageId == id select m;
if (resultFormat == "json")
{
return Json(messages, JsonRequestBehavior.AllowGet); // case 2
}
else
{
return View(messages); // case 1
}
}
これがURLシナリオです
Home/Index/1
ケース1に進みますHome/Index/1.html
ケース1に進みますHome/Index/1.json
ケース2に進みます
これはうまく機能します。しかし、私は文字列をチェックするのが嫌いです。コントローラメソッドのパラメータ
として使用される列挙型をどのように実装しますか?
基本的な考え方を説明するためのいくつかの擬似コード:resultFormat
namespace Models
{
public enum ResponseType
{
HTML = 0,
JSON = 1,
Text = 2
}
}
MapRoute:
MapRoute(
"ResultFormat",
"{controller}/{action}/{id}.{resultFormat}",
new {
controller = "Home",
action = "Index",
id = 0,
resultFormat = Models.ResultFormat.HTML
}
);
コントローラメソッドのシグネチャ:
public ActionResult Index(Int32 id, Models.ResultFormat resultFormat)