3

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

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

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

4

1 回答 1

11

发现这很有趣,正如@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);
    }
}

更新

如果要注入的不是动态数据,直接去掉filter构造函数和硬编码key&value,就可以全局注册filter而不需要修改controller GlobalFilters.Filters.Add(new PropertyInjector());

于 2017-02-10T14:56:50.647 回答