[英]Web API: Configure JSON serializer settings on action or controller level
Overriding the default JSON serializer settings for web API on application level has been covered in a lot of SO threads.在应用程序级别覆盖 Web API 的默认 JSON 序列化器设置已在许多 SO 线程中进行了介绍。 But how can I configure its settings on action level?但是如何在操作级别配置其设置? For example, I might want to serialize using camelcase properties in one of my actions, but not in the others.例如,我可能想在我的一个操作中使用驼峰属性进行序列化,但不想在其他操作中进行序列化。
At action level you may always use a custom JsonSerializerSettings
instance while using Json
method:在操作级别,您可以在使用Json
方法时始终使用自定义JsonSerializerSettings
实例:
public class MyController : ApiController
{
public IHttpActionResult Get()
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var model = new MyModel();
return Json(model, settings);
}
}
You may create a new IControllerConfiguration
attribute which customizes the JsonFormatter:您可以创建一个新的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);
}
}
Here's an implementation of the above as 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);
}
}
I needed to return a 404 status error code alongside a json object with error details.我需要在带有错误详细信息的 json 对象旁边返回 404 状态错误代码。 I solved it using WebApi.Content with a new new JsonMediaTypeFormatter.我使用 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.