我们正在尝试将旧API迁移到我们当前的.Net Core Web API中。我们当前的API使用camelCasing返回JSON,但我们的旧API使用PascalCasing,我们不想更新客户端。
有没有办法指定我们想要为每个控制器使用哪种序列化策略,而不是整个服务的全局?
答案 0 :(得分:6)
Yes, you can achieve it by using attribute on your controller. See the sample below:
[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);
}
}
and here is your controller:
[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);
}
}
答案 1 :(得分:-1)
我为OkObjectResult做了一个扩展方法,可以选择我不希望驼峰式序列化行为的地方。您可以像这样使用它:
OkObjectResult(yourResponseObject).PreventCamelCase();
以下是扩展方法:
public static OkObjectResult PreventCamelCase(this OkObjectResult response)
{
var settings = JsonSerializerSettingsProvider.CreateSerializerSettings();
settings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
var formatter = new JsonOutputFormatter(settings, ArrayPool<Char>.Shared);
response.Formatters.Add(formatter);
return response;
}