UPDATE

谢谢你的回答.我正在进行一个新项目,看起来我终于弄清了这一点:看起来实际上应该归咎于以下代码:

public static HttpResponseMessage GetHttpSuccessResponse(object response, HttpStatusCode code = HttpStatusCode.OK)
{
    return new HttpResponseMessage()
    {
        StatusCode = code,
        Content = response != null ? new JsonContent(response) : null
    };
}

在别处

public JsonContent(object obj)
{
    var encoded = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore } );
    _value = JObject.Parse(encoded);

    Headers.ContentType = new MediaTypeHeaderValue("application/json");
}

我忽略了看似无害的JsonContent,假设它是WebAPI,但不是.

这是用everywhere...我能第一个说吗,wtf?或者应该是"他们为什么这么做?"


original question follows

有人会认为这是一个简单的配置设置,但我已经逃避太久了.

我研究了各种解决方案和答案:

https://gist.github.com/rdingwall/2012642

似乎不适用于最新的WebAPI版本...

以下方法似乎不起作用-属性名称仍然使用PascalCase.

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

json.UseDataContractJsonSerializer = true;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

Mayank在这里的答案是:CamelCase JSON WebAPI Sub-Objects (Nested objects, child objects)似乎是一个不令人满意但可行的答案,直到我意识到这些属性必须添加到生成的代码中,因为我们正在使用linq2sql...

有没有办法自动做到这一点?这个"肮脏"已经困扰我很长一段时间了.

推荐答案

把这些放在一起你会...

protected void Application_Start()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
}

.net相关问答推荐

Docker失败文件找不到

安装特定主要版本的DotNet SDK最新版本

MSBuild:CopyToOutputDirectory不会将本机DLL复制到输出

如何使用AWS Lambda函数制作网络挂钩?

部署时如何控制红隼端口?

为什么 GetShortestDayName 返回的名称比预期的短?

当 Func 委托需要接口作为参数时,它是如何工作的?

如何使用 C# 关键字作为属性名称?

.NET 应用程序的链接器状态(又名请先生,我可以有一个链接器2009 年版)

在 Moq 中模拟泛型方法而不指定 T

mstest.exe 在哪里?

C# 中的 myCustomer.GetType() 和 typeof(Customer) 有什么区别?

如何制作通用类型转换函数

如何使用 Entity Framework Code First CTP 5 存储图像?

如何获得 Bin 路径?

如何找到二维数组的大小?

ADO.NET Entity Framework:更新向导不会添加表

模拟和单元测试需要时如何抛出 SqlException?

当它被抛出和捕获时,不要在那个异常处停止调试器

如何将我的应用程序窗口置于最前面?