如果控制器方法的返回类型是接口,您还可以应用操作过滤器来仅序列化接口属性。这样,您始终与接口定义保持同步,而无需更改实现接口的类的任何属性。
为此,您首先必须创建一个自定义InterfaceContractResolver
合同解析器,如下所述:
public class InterfaceContractResolver : DefaultContractResolver
{
private readonly Type _interfaceType;
public InterfaceContractResolver(Type interfaceType)
{
_interfaceType = interfaceType;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(_interfaceType, memberSerialization);
return properties;
}
}
然后添加一个操作过滤器(作为此处解释的属性或全局,如果您希望将此作为默认行为)查看控制器方法的返回类型,如果它是一个接口,则使用上面定义的合同解析器:
public class InterfaceFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
if (content != null)
{
Type returnType = actionExecutedContext.ActionContext.ActionDescriptor.ReturnType;
if (returnType.IsInterface && content.Formatter is JsonMediaTypeFormatter)
{
var formatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
ContractResolver = new InterfaceContractResolver(returnType)
}
};
actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, formatter);
}
}
}
}