动机:Google JSON样式指南,我想在我的其余API中插入一些自定义序列化逻辑。我正在使用WebAPI 2和JSON.NET。我的目标是将响应的“有效负载”包装在主JSON响应的“数据”字段中,如样式指南中所述,在每个响应中都包含一个apiVersion字段,以及类似的东西。当然,控制器操作只会返回直接的POCO,而我想修改它们发送到的容器,而不是POCO本身,因此:
{
"id": "111",
"apiVersion": "1.0",
"data": {
"kind": "monkey",
"name": "manny",
"age": "3"
},
"error": null
}
...那种东西 因此,我设想在每个响应通过网络之前将少量标准数据插入到每个响应中。做到这一点的最佳方法是什么?
TIA。
我相信您可以使用ActionFilterAttribute
来实现这种行为。首先,您需要创建一个类来表示包装的响应(所有属性均为字符串,根据需要进行调整):
public class WrappedJsonResponse
{
public string Id {get;set;}
public string ApiVersion {get;set;}
public object Data {get;set;}
public string Error {get;set;}
}
将ActionFilterAttribute
允许您通过虚拟动作的执行后做一些处理OnActionExecuted
方法:
public class WrappedJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext context)
{
// A POCO response will normally be wrapped in an ObjectContent
var content = context.Response.Content as ObjectContent
if(content != null)
{
// Create the WrappedJsonResponse object appropriately and
// put the original result in the Data property
content.Value = new WrappedJsonResponse { Data = content.Value };
content.ObjectType = typeof(WrappedJsonResponse);
}
}
}
使用该属性,然后可以选择将其应用于所需的位置(整个控制器,仅操作或作为默认过滤器)。
注意:目前,我无法访问开发环境,也没有测试过滤器。如果这还不完整,那么它至少应该使您对如何完成操作有所了解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句