Web API:在操作或控制器级别配置 JSON 序列化程序设置 [英] Web API: Configure JSON serializer settings on action or controller level

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

问题描述

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

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 序列化程序设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆