【发布时间】:2009-03-26 17:20:56
【问题描述】:
我使用 ASP.NET MVC 的第二天和我第一次请求 SO 上的代码(是的,走捷径)。
我正在寻找一种方法来创建一个过滤器,该过滤器拦截来自 Action 的当前输出,而是输出 JSON(我知道 alternate approaches,但这是为了帮助我理解过滤器)。我想忽略与该操作相关的任何视图,只需获取 ViewData["Output"],将其转换为 JSON 并将其发送到客户端。需要填写的空白:
TestController.cs:
[JSON]
public ActionResult Index()
{
ViewData["Output"] = "This is my output";
return View();
}
JSONFilter.cs:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
/*
* 1. How to override the View template and set it to null?
* ViewResult { ViewName = "" } does not skip the view (/Test/Index)
*
* 2. Get existing ViewData, convert to JSON and return with appropriate
* custom headers
*/
}
更新:社区的回答导致filter for JSON/POX 的实现更全面。
【问题讨论】:
标签: c# asp.net-mvc json action-filter