。Net Core 3.0:仅将AddJsonOptions应用于特定的控制器

问题描述 投票:4回答:1

我有两个控制器FooControllerBooController(最后一个是向后兼容的,我希望只有FooController会返回其模型带有大写驼峰表示法(“ UpperCamelCase”)。

例如:

public class MyData 
{
    public string Key {get;set;}
    public string Value {get;set;} 
}

public class BooController : ControllerBase 
{
    public ActionResult<MyData> GetData() { ... } 
} 
public class FooController : ControllerBase 
{
    public ActionResult<MyData> GetData() { ... } 
}

所需的GET输出:

GET {{domain}}/api/Boo/getData 
[
    {
        "key": 1,
        "value": "val"
    } 
]

GET {{domain}}/api/Foo/getData 
[
    {
        "Key": 1,
        "Value": "val"
    } 
]

[如果我将AddJsonOptions扩展名和option.JsonSerializerOptions.PropertyNamingPolicy = null一起使用,则为:

services.AddMvc()
.AddJsonOptions(option =>
{
    option.JsonSerializerOptions.PropertyNamingPolicy = null;
});

BooControllerFooController都返回带有大写驼峰表示法的数据。

如何仅使FooController返回大驼峰格式的数据?

asp.net-mvc .net-core
1个回答
0
投票

已解决(尽管性能较差且解决方案有些拙劣-希望有人提出更好的解决方案:]

在旧版BooController内部,我正在使用JsonSerializerSettings的自定义格式化程序返回响应之前对响应进行序列化:

public class BooController : ControllerBase 
{
    public ActionResult<MyData> GetData() 
    {
        var formatter = JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        return Ok(JsonConvert.SerializeObject(response, Formatting.Indented, formatter()));
    } 
}

结果:

GET {{domain}}/api/Boo/getData 
[
    {
        "key": 1,
        "value": "val"
    } 
]
© www.soinside.com 2019 - 2024. All rights reserved.