在许多SO线程中已经涵盖了在应用程序级别覆盖Web API的默认JSON序列化程序设置。但是如何在动作级别配置其设置?例如,我可能希望在我的一个操作中使用camelcase属性进行序列化,但不能在其他操作中进行序列化。
答案 0 :(得分:42)
在操作级别,您可以在使用JsonSerializerSettings
方法时始终使用自定义Json
实例:
public class MyController : ApiController
{
public IHttpActionResult Get()
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var model = new MyModel();
return Json(model, settings);
}
}
您可以创建一个新的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);
}
}
答案 1 :(得分:3)
以下是上述作为操作属性的实现:
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);
}
}
答案 2 :(得分:0)
我需要返回404状态错误代码以及带有错误详细信息的json对象。我使用WebApi.Content和新的新JsonMediaTypeFormatter解决了该问题。
public class MyController : ApiController
{
public IHttpActionResult Get()
{
// Configure new Json formatter
var formatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
TypeNameHandling = TypeNameHandling.None,
PreserveReferencesHandling = PreserveReferencesHandling.None,
Culture = CultureInfo.InvariantCulture,
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
}
};
try
{
var model = new MyModel();
return Content(HttpStatusCode.OK, model, formatter);
}
catch (Exception err)
{
var errorDto = GetErrorDto(HttpStatusCode.NotFound, $"{err.Message}");
return Content(HttpStatusCode.NotFound, errorDto, formatter);
}
}
}