问题描述
通过在我的 Startup.cs
中使用以下内容,我设法将 api 响应 序列化为 snake_case
命名约定.通过这种方式,它将我的 DTO 返回为蛇形 JSON.
I've managed to serialize the api responses to the snake_case
naming convention by using the following in my Startup.cs
. This way it returns my DTO's as snake cased JSON.
services
.AddMvc()
.AddJsonOptions(x =>
{
x.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
});
这就是我想要的一半.但是当我发布蛇形 JSON 时,请参见下面的示例,它不会将值绑定到 api 上的 DTO.例如,UserProfile
数组和 CreatedOn
、ModifiedOn
没有得到任何值.
That is the half of what I want. But when I post snake-cased JSON, see below for an example, it will not bind the values to my DTO on the api. For example the UserProfile
array and the CreatedOn
, ModifiedOn
are not getting any values.
{
"user_profiles": [
{
"id": 1,
"created_on": "2017-02-08T19:54:59.370Z",
"modified_on": "2017-02-18T14:10:42.248Z",
"email": "[email protected]",
"username": "my_username"
}
],
"id": 1,
"created_on": "2017-02-08T19:50:31.690Z",
"modified_on": 2017-02-08T19:50:31.690Z,
"name": "My Company Name"
}
设置它以便 API 在发送到 api 时处理蛇形 JSON 的正确方法是什么并在从 api 请求时将其作为蛇形发送?
What is the proper way to set it up so that the API handles snake cased JSON when send to the api and send it as snake case when requested from the api?
我的 DTO
public class CompanyDto
{
public int Id { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string Name { get; set; }
public IEnumerable<UserProfileDto> UserProfiles { get; set; }
}
public class UserProfileDto
{
public int Id { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string Email { get; set; }
public string Username { get; set; }
}
我在控制器上的 PUT 操作
My PUT action on the controller
[HttpPut("{id}")]
public async Task<IActionResult> Put(int id, [FromBody]CompanyDto value)
{
// Body
}
好吧,事实证明我在发布到 API 的 JSON 中遗漏了一些值.它们是 api 需要的,但没有得到任何错误或其他东西.
Alright turns out that I was missing some values in the JSON I posted to the API. They were required by the api but did not get any error or somethings.
所以要回答这个问题,根据我的经验,使用以下内容足以为 dotnet 核心 api 对 JSON 输出/输入进行蛇形外壳.相反,它只是让预期的模型 null
叹息.
So to answer the question, in my experience using the following is enough for snake casing the JSON output / input for a dotnet core api. Instead it just made the expected model null
sigh.
services
.AddMvc()
.AddJsonOptions(x =>
{
x.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
});
推荐答案
你忘记了引用:
"modified_on": 2017-02-08T19: 50: 31.690Z,
改变这一点,同样有效.
Changing this, works as well.
这篇关于如何为 dotnet 核心 api 正确设置蛇案例 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!