Specific JSON settings per controller on ASP.NET MVC 6

前端 未结 2 1634
独厮守ぢ
独厮守ぢ 2020-12-31 08:37

I need specific JSON settings per controller in my ASP.NET MVC 6 webApi. I found this sample that works (I hope !) for MVC 5 : Force CamelCase on ASP.NET WebAPI Per Control

2条回答
  •  时光取名叫无心
    2020-12-31 09:15

    You can use a return type of JsonResult on your controller action methods. In my case, I needed specific actions to return Pascal Case for certain legacy scenarios. The JsonResult object allows you to pass an optional parameter as the JsonSerializerSettings.

    public JsonResult Get(string id)
    {
        var data = _service.getData(id);
    
        return Json(data, new JsonSerializerSettings
        {
            ContractResolver = new DefaultContractResolver()
        });
    
    }
    

    To have more consistent controller method signatures I ended up creating an extension method:

    public static JsonResult ToPascalCase(this Controller controller, object model)
    {
        return controller.Json(model, new JsonSerializerSettings
        {
            ContractResolver = new DefaultContractResolver()
        });
    }
    

    Now I can simply call the extension method inside my controller like below:

    public IActionResult Get(string id)
    {
        var data = _service.getData(id);
        return this.ToPascalCase(data);
    }
    

提交回复
热议问题