【问题标题】:ASP.NET MVC: How to create an action filter to output JSON?ASP.NET MVC:如何创建一个动作过滤器来输出 JSON?
【发布时间】: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


    【解决方案1】:

    我建议您真正想要做的是使用模型而不是任意的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 行需要更正为 ((ViewResultBase)filterContext.Result)).ViewData.Model。但是,即使 filterContext.Result 具有正确的值,Index() 操作仍会显示与其关联的视图(Views/Test/Index),而不是显示 JSON blob。
    • 在 OnActionExecuted 中执行此操作会覆盖视图并实现我所追求的。
    • 嗯。我会认为在渲染结果之前替换结果将是适当的时间。我会更新我的答案。
    【解决方案2】:

    您没有提到只有条件地返回 JSON,所以如果您希望操作每次都返回 JSON,为什么不使用:

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

    【讨论】:

    • [JSON] 属性用于在某些操作上打开或关闭 JSON,但正如我所提到的,这更像是一个练习。在实际实现中,我可能会检查请求 http 标头以确定响应类型。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 2010-11-06
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      相关资源
      最近更新 更多