C# 扩展CamelCasePropertyNamesContractResolver无效

C# 扩展CamelCasePropertyNamesContractResolver无效,c#,json,json.net,asp.net-web-api2,camelcasing,C#,Json,Json.net,Asp.net Web Api2,Camelcasing,我扩展了Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver,并在我的WebApi中应用了新的解析器: public static void Register(HttpConfiguration config) { var json = config.Formatters.JsonFormatter.SerializerSettings; json.ContractResolver = new C

我扩展了Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver,并在我的WebApi中应用了新的解析器:

public static void Register(HttpConfiguration config)
{
    var json = config.Formatters.JsonFormatter.SerializerSettings;
    json.ContractResolver = new CustomPropertyNamesContractResolver();
    json.Formatting = Formatting.Indented;

    config.MapHttpAttributeRoutes();
}
下面是我的自定义名称解析器(CustomPropertyNamesContractResolver类)的重写方法:

我的问题是,结果确实是骆驼式的,但像“QuestionID”这样的属性永远不会转换为“QuestionID”-我一直收到的是“QuestionID”

另外,我的自定义ResolvePropertyName()方法从未被调用(使用断点对其进行测试),因此似乎只有父类(CamelCasePropertyNamesContractResolver)的ResolvePropertyName()方法以某种方式被调用

现在,当我直接从DefaultContractResolver(它是CamelCasePropertyNamesContractResolver的父级)继承时,我的自定义ResolvePropertyName()方法被调用

有人能解释一下这里发生了什么吗? 我遗漏了什么吗?

不再由
CamelCasePropertyNamesContractResolver调用。该文件记录如下:

JamesNK于2016年7月4日发表评论

是的,现在就要破裂了。该方法[ResolvePropertyName]从未被调用,因为CamelCasePropertyNamesContractResolver的工作方式发生了变化

您可以做的是继承CamelCaseNamingStrategy并执行类似的操作,然后将其分配给DefaultContractResolver。请注意,您应该在静态变量上缓存协定解析程序,这样它就不会一直被重新创建

按照此处的建议,您应该从like so继承:

然后像这样设置它:

或者,由于我认为ASP.NET Web API使用自己的协定解析程序,您可能希望修改现有的
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver
NamingStrategy
,假设已在设置中分配了一个解析程序:

var resolver = json.ContractResolver as DefaultContractResolver ?? new DefaultContractResolver();
resolver.NamingStrategy = new CustomNamingStrategy();
json.ContractResolver  = resolver;

(注意-我自己没有使用预先存在的冲突解决程序进行测试。)

这种行为的原因是CamelCasePropertyNamesContractResolver.ResolvePropertyName()的签名吗,它是以下内容?受保护的内部重写字符串ResolvePropertyName(字符串propertyName)
public class CustomNamingStrategy : CamelCaseNamingStrategy
{
    protected override string ResolvePropertyName(string propertyName)
    {
        if (propertyName.Equals("ID"))
            return "id";

        // return the camelCase
        propertyName = base.ResolvePropertyName(propertyName);

        if (propertyName.EndsWith("ID"))
            propertyName = propertyName.Substring(0, propertyName.Length - 1) + "d";
        return propertyName;
    }
}
json.ContractResolver = new DefaultContractResolver { NamingStrategy = new CustomNamingStrategy() };
var resolver = json.ContractResolver as DefaultContractResolver ?? new DefaultContractResolver();
resolver.NamingStrategy = new CustomNamingStrategy();
json.ContractResolver  = resolver;