我们有一个 ASP.NET 应用程序。我们无法编辑 Controller 的源代码。但是我们可以实现ActionFilter。
我们的 Controller 操作方法之一返回 JSON。是否可以在 ActionFilter 中对其进行修改?我们需要为返回的对象再添加一个属性。
也许,还有其他方法可以实现它?
最佳答案
发现这很有趣,正如@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);
}
}
更新
如果要注入(inject)的不是动态数据,则直接移除过滤器构造函数和硬编码键值,然后过滤器可以在全局注册,无需编辑 Controller
GlobalFilters.Filters.Add(new PropertyInjector());
关于ASP.NET。如何修改返回的 JSON (actionfilter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42155843/