我使用 ASP.NET MVC 的第二天和我对 SO 代码的第一次请求(是的,走捷径)。
我正在寻找一种方法来创建一个过滤器,该过滤器拦截 Action 的当前输出,而不是输出 JSON(我知道 alternate approaches,但这是为了帮助我理解过滤器)。我想忽略与该操作关联的任何 View ,只获取 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 的更全面实现.
最佳答案
我建议您真正想要做的是使用模型而不是任意 ViewData
元素并覆盖 OnActionExecuted
而不是 OnActionExecuting
。这样,您只需在结果执行并呈现给浏览器之前用您的 JsonResult
替换结果。
public class JSONAttribute : ActionFilterAttribute
{
...
public override void OnActionExecuted( ActionExecutedContext filterContext)
{
var result = new JsonResult();
result.Data = ((ViewResult)filterContext.Result).Model;
filterContext.Result = result;
}
...
}
[JSON]public ActionResult Index()
{
ViewData.Model = "This is my output";
return View();
}
关于c# - ASP.NET MVC : How to create an action filter to output JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/686753/