我已经成功序列化了 api回应 to the snake_case
在我的中使用以下命名约定Startup.cs
。这样它就会以蛇形 JSON 形式返回我的 DTO。
services
.AddMvc()
.AddJsonOptions(x =>
{
x.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
});
这就是我想要的一半。但是,当我发布蛇形 JSON 时(请参阅下面的示例),它不会将值绑定到 api 上的 DTO。例如UserProfile
数组和CreatedOn
, ModifiedOn
没有得到任何值。
{
"user_profiles": [
{
"id": 1,
"created_on": "2017-02-08T19:54:59.370Z",
"modified_on": "2017-02-18T14:10:42.248Z",
"email": "[email protected] /cdn-cgi/l/email-protection",
"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 时处理蛇形格式的 JSONand当 API 请求时将其作为蛇包发送?
My DTO's
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 操作
[HttpPut("{id}")]
public async Task<IActionResult> Put(int id, [FromBody]CompanyDto value)
{
// Body
}
EDIT:
好吧,事实证明我在发布到 API 的 JSON 中缺少一些值。 api 需要它们,但没有收到任何错误或其他信息。
因此,为了回答这个问题,根据我的经验,使用以下内容足以蛇形封装 dotnet core api 的 JSON 输出/输入。相反,它只是制作了预期的模型null
sigh.
services
.AddMvc()
.AddJsonOptions(x =>
{
x.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
});