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

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

本文介绍了Web API:在操作或控制器级别配置JSON序列化程序设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多SO线程已涵盖了在应用程序级别覆盖Web API的默认JSON序列化程序设置.但是如何在操作级别配置其设置?例如,我可能想在其中一个操作中使用驼峰属性进行序列化,而在其他操作中则不需要.

Overriding the default JSON serializer settings for web API on application level has been covered in a lot of SO threads. 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.

推荐答案

选项1(最快)

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

Option 1 (quickest)

At action level you may always use a custom JsonSerializerSettings instance while using Json method:

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:

Option 2 (controller level)

You may create a new IControllerConfiguration attribute which customizes the 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);
    }
}

这篇关于Web API:在操作或控制器级别配置JSON序列化程序设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 14:47