ASP.NET MVC:如何创建一个动作过滤器输出JSON? [英] ASP.NET MVC: How to create an action filter to output JSON?

查看:580
本文介绍了ASP.NET MVC:如何创建一个动作过滤器输出JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第二天与ASP.NET MVC和code上,所以我的第一个请求(是的,抄近路)。

My second day with ASP.NET MVC and my first request for code on SO (yep, taking a short cut).

我要寻找一种方法来创建一个过滤器,截取从动作电流输出,而是输出JSON(我知道的<一个href=\"http://weblogs.asp.net/omarzabir/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx\"相对=nofollow>其他方法但这是帮助我理解过滤器)。我想忽略与操作相关的任何意见,只是抢计算机[输出],将其转换为JSON并将其发送出去的客户端。空白填补:

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

更新:社区解答导致了一个的为JSON / POX 过滤器。

推荐答案

我建议你真正想要做的是使用模型,而不是任意的ViewData元素,并覆盖OnActionExecuted而不是OnActionExecuting。之前被执行,从而呈现给浏览器与你的JsonResult这种方式,您只需更换的结果。

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. That way you simply replace the result with your JsonResult before it gets executed and thus rendered to the browser.

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();
}

这篇关于ASP.NET MVC:如何创建一个动作过滤器输出JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆