c# - ASP.NET MVC : How to create an action filter to output JSON?

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

我使用 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/

相关文章:

asp.net - 如果我没有为操作方法指定 [httpGet] 或 [httpPost],调用它的规则是什么

php - 如何更改从 PHP 中的 MySQL 查询返回的数据格式

java - 反序列化Json,结构相同但字段名不同

ajax - 在 ASP.NET MVC 3 中使用 Ajax 和 JsonResult

c# - 大数据量的 MemoryStream 替代方案

c# - 如何让操作事件在包含 ScrollViewer 子元素的元素上起作用

c# - 在 C# 的事件日志中使用自定义 View (过滤器)

asp.net-mvc - 为什么 EF4 试图重新创建我的数据库,即使模型没有改变?

asp.net-mvc - Asp.Net core MVC6如何在Identity 3中初始添加角色

c# - System.Data.OracleClient 不适用于 64 位 Oracle 客户端