好的,我知道该怎么做。我们需要以这种方式使用自定义 DefaultContractResolver:
public class ExcludeEntityKeyContractResolver : DefaultContractResolver
{
private static Type mCollectionType = typeof(System.Data.Objects.DataClasses.RelatedEnd);
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var members = GetSerializableMembers(type);
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
IList<JsonProperty> serializeProperties = new List<JsonProperty>();
for (int i = 0; i < properties.Count; i++)
{
var memberInfo = members.Find(p => p.Name == properties[i].PropertyName);
if (!memberInfo.GetCustomAttributes(false).Any(a => a is SoapIgnoreAttribute) && properties[i].PropertyType != typeof(System.Data.EntityKey))
{
serializeProperties.Add(properties[i]);
}
}
return serializeProperties;
}
}
在 Global.asax 中:
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new ExcludeEntityKeyContractResolver();
var jsonMediaTypeFormatter = new JsonMediaTypeFormatter();
jsonMediaTypeFormatter.SerializerSettings = serializerSettings;
GlobalConfiguration.Configuration.Formatters.Insert(0, jsonMediaTypeFormatter);
并且不用担心性能,因为在整个应用程序持续时间内,每种类型只会调用一次 CreateProperties :)