每个控制器都有.Net Core Web API不同的JSON大小写

Zac*_*and 4 serialization json asp.net-core

我们正在尝试将旧API迁移到我们当前的.Net Core Web API中.我们当前的API使用camelCasing返回JSON,但我们的旧API使用PascalCasing,我们不想更新客户端.

有没有办法指定我们想要为每个控制器使用哪种序列化策略,而不是整个服务的全局?

arm*_*che 7

是的,您可以使用控制器上的属性来实现它.请参阅以下示例:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomJsonFormatter : ActionFilterAttribute
{
    private readonly string formatName = string.Empty;
    public CustomJsonFormatter(string _formatName)
    {
        formatName = _formatName;
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        if (context == null || context.Result == null)
        {
            return;
        }

        var settings = JsonSerializerSettingsProvider.CreateSerializerSettings();

        if (formatName == "camel")
        {
            settings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
        }            
        else
        {
            settings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
        }

        var formatter = new JsonOutputFormatter(settings, ArrayPool<Char>.Shared);

        (context.Result as Microsoft.AspNetCore.Mvc.OkObjectResult).Formatters.Add(formatter);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是你的控制器:

[CustomJsonFormatter("camel")]
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET: api/values
    [HttpGet]
    public IActionResult Get()
    {
        Car car = new Car { Color = "red", Make = "Nissan" };

        return Ok(car);
    }        
}
Run Code Online (Sandbox Code Playgroud)