考虑这个 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
将转到案例 1Home/Index/1.html
将转到案例 1Home/Index/1.json
将转到案例 2
这很好用。但我讨厌检查字符串。如何实现一个枚举作为resultFormat
控制器方法中的参数?
一些伪代码来解释基本思想:
namespace Models
{
public enum ResponseType
{
HTML = 0,
JSON = 1,
Text = 2
}
}
地图路线:
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)