ASP.NET。如何修改返回的JSON(actionfilter)

时间:2017-02-10 09:29:26

标签: asp.net json asp.net-mvc

我们有一个ASP.NET应用程序。我们无法编辑控制器的源代码。但是我们可以实现ActionFilter。

我们的一个控制器操作方法返回JSON。是否可以在ActionFilter中修改它?我们需要为返回的对象添加一个属性。

也许,还有其他方法可以实现它吗?

1 个答案:

答案 0 :(得分:7)

发现这很有意思,正如@Chris所提到的那样,虽然从概念上讲我知道这会起作用,但我从来没有尝试过,因此想过给它一个机会。我不确定这是否是一种优雅/正确的方式,但这对我有用。 (我尝试使用Age动态添加ActionResult属性)

    [PropertyInjector("Age", 12)]
    public ActionResult Index()
    {
        return Json(new { Name = "Hello World" }, JsonRequestBehavior.AllowGet);
    }

过滤器:

public class PropertyInjector : ActionFilterAttribute
{
    string key;
    object value;
    public PropertyInjector(string key, object value)
    {
        this.key = key;
        this.value = value;
    }
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var jsonData = ((JsonResult)filterContext.Result).Data;
        JObject data = JObject.FromObject(jsonData);
        data.Add(this.key,JToken.FromObject(this.value));

        filterContext.Result = new ContentResult { Content = data.ToString(), ContentType = "application/json" };

        base.OnActionExecuted(filterContext);
    }
}

更新

如果它不是要注入的动态数据,则删除过滤器构造函数和硬编码密钥&直接值,然后可以全局注册过滤器而无需编辑控制器 GlobalFilters.Filters.Add(new PropertyInjector());

相关问题