简体   繁体   English

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

[英]ASP.NET MVC: How to create an action filter to output JSON?

My second day with ASP.NET MVC and my first request for code on SO (yep, taking a short cut). 我在ASP.NET MVC上的第二天,也是我第一次在SO上请求代码(是的,快捷方式)。

I am looking for a way to create a filter that intercepts the current output from an Action and instead outputs JSON (I know of alternate approaches but this is to help me understand filters). 我正在寻找一种方法来创建一个过滤器,拦截一个Action的当前输出,而不是输出JSON(我知道其他方法,但这是为了帮助我理解过滤器)。 I want to ignore any views associated with the action and just grab the ViewData["Output"], convert it to JSON and send it out the client. 我想忽略与该操作相关的任何视图,只需抓取ViewData [“Output”],将其转换为JSON并将其发送出客户端。 Blanks to fill: 空白填补:

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
    */
}

Update: Community answers led to a fuller implementation for a filter for JSON/POX . 更新:社区答案导致更全面地实施JSON / POX过滤器

I would suggest that what you really want to do is use the Model rather than arbitrary ViewData elements and override OnActionExecuted rather than OnActionExecuting . 我建议你真正想做的是使用Model而不是任意的ViewData元素,并覆盖OnActionExecuted而不是OnActionExecuting That way you simply replace the result with your JsonResult before it gets executed and thus rendered to the browser. 这样,您只需将结果替换为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();
}

You haven't mentioned only returning the JSON conditionally, so if you want the action to return JSON every time, why not use: 您没有提到仅有条件地返回JSON,因此如果您希望操作每次都返回JSON,为什么不使用:

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

maybe this post could help you the right way. 也许这篇文章可以帮助你正确的方式。 The above post is also a method 上面的帖子也是一种方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM