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

时间:2017-06-12 12:07:33

标签: c# asp.net-web-api json.net

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

3 个答案:

答案 0 :(得分:42)

选项1(最快)

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

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);
    }
}

答案 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);
        }
    }
}