如果控制器方法的返回類型是接口,那麼您還可以應用操作篩選器來僅序列化接口屬性。這樣您就可以始終保持與接口定義的同步,而無需更改實現接口的類的任何屬性。
對於這個你首先必須創建一個自定義InterfaceContractResolver
合同分解爲解釋here:
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;
}
}
然後添加一個動作過濾器(無論是作爲屬性作爲解釋here或全球範圍內,如果你想這是一個默認的行爲),看起來在控制器方法的返回類型,如果它是一個接口使用上面定義的合同解析:
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);
}
}
}
}
您可以詳細瞭解複雜的方法的位或發送一個鏈接到一些例子。 .. – Mortalus