考虑一下这个图路线:
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(
"ResultFormat",
"{controller}/{action}/{id}.{resultFormat}",
new {
controller = "Home",
action = "Index",
id = 0,
resultFormat = Models.ResultFormat.HTML
}
);
控制器方法的签名:
public ActionResult Index(Int32 id, Models.ResultFormat resultFormat)
恕我直言响应格式是一个横切关注点,它不是控制器惹它。 我建议你写一个ActionFilter这个工作:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public sealed class RespondToAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var resultFormat = filterContext.RouteData.Values["resultFormat"] as string ?? "html";
ViewResult viewResult = filterContext.Result as ViewResult;
if (viewResult == null)
{
// The controller action did not return a view, probably it redirected
return;
}
var model = viewResult.ViewData.Model;
if (string.Equals("json", resultFormat, StringComparison.OrdinalIgnoreCase))
{
filterContext.Result = new JsonResult { Data = model };
}
// TODO: you could add some other response types you would like to handle
}
}
然后简化您的控制器操作了一下:
[RespondTo]
public ActionResult Index(int id)
{
var messages = new string[0];
if (id > 0)
{
// TODO: Fetch messages from somewhere
messages = new[] { "message1", "message2" };
}
return View(messages);
}
该ActionFilter是,你可以应用到其他的动作可重复使用的组件。
你的伪代码将正常工作。 默认ModelBinder的自动转换在URL中Models.ResultFormat枚举的字符串。 但是,这将是更明智ActionFilter,作为所述达林季米特洛夫。
这是我想出了ActionFilter:
public sealed class AlternateOutputAttribute :
ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext aec)
{
ViewResult vr = aec.Result as ViewResult;
if (vr == null) return;
var aof = aec.RouteData.Values["alternateOutputFormat"] as String;
if (aof == "json") aec.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = vr.ViewData.Model,
ContentType = "application/json",
ContentEncoding = Encoding.UTF8
};
}
}