Web API:在操作或控制器级别配置JSON序列化程序设置

在应用程序级别覆盖Web API的默认JSON序列化程序设置已涵盖在许多SO线程中。 但是如何在动作级别配置其设置? 例如,我可能希望在我的一个操作中使用camelcase属性进行序列化,但不能在其他操作中进行序列化。

选项1(最快)

在操作级别,您可以在使用Json方法时始终使用自定义JsonSerializerSettings实例:

 public class MyController : ApiController { public IHttpActionResult Get() { var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var model = new MyModel(); return Json(model, settings); } } 

选项2(控制器级别)

您可以创建一个新的IControllerConfiguration属性来自定义JsonFormatter:

 public class CustomJsonAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { var formatter = controllerSettings.Formatters.JsonFormatter; controllerSettings.Formatters.Remove(formatter); formatter = new JsonMediaTypeFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() } }; controllerSettings.Formatters.Insert(0, formatter); } } [CustomJson] public class MyController : ApiController { public IHttpActionResult Get() { var model = new MyModel(); return Ok(model); } } 

以下是Action Attribute的实现:

 public class CustomActionJsonFormatAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext?.Response == null) return; var content = actionExecutedContext.Response.Content as ObjectContent; if (content?.Formatter is JsonMediaTypeFormatter) { var formatter = new JsonMediaTypeFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() } }; actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, formatter); } } } public class MyController : ApiController { [CustomActionJsonFormat] public IHttpActionResult Get() { var model = new MyModel(); return Ok(model); } }