ASP.NET MVC:如何创建一个动作过滤器来输出JSON?

时间:2009-03-26 17:20:57

标签: c# asp.net-mvc json action-filter

我使用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的更全面实施。

3 个答案:

答案 0 :(得分:4)

我建议您真正想要做的是使用模型而不是任意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();
}

答案 1 :(得分:3)

您没有提到仅有条件地返回JSON,因此如果您希望每次都返回JSON,为什么不使用:

public JsonResult Index()
{
    var model = new{ foo = "bar" };
    return Json(model);
}

答案 2 :(得分:0)

也许这个post可以帮助你正确的方式。以上帖子也是一种方法