只能使用特定动作骆驼系列化 [英] use camel case serialization only for specific actions

查看:144
本文介绍了只能使用特定动作骆驼系列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用的WebAPI了一段时间,一般设置为使用骆驼情况下JSON序列化,这是目前比较普遍和幸福无处不记录。

I've used WebAPI for a while, and generally set it to use camel case json serialization, which is now rather common and well documented everywhere.

然而,最近在一个更大的项目时,我遇到了一个更具体的要求:我们需要使用骆驼情况下JSON序列化,但由于与我们的客户脚本的向后兼容性的问题,我只希望它发生的具体行动,以避免破坏(超大型)网站的其他部分。

Recently however, working on a much larger project, I came across a more specific requirement: we need to use camel case json serialization, but because of backward compatibility issues with our client scripts, I only want it to happen for specific actions, to avoid breaking other parts of the (extremely large) website.

我想,一个选择是有一个自定义的内容类型,但是那需要客户端code指定它。

I figure one option is to have a custom content type, but that then requires client code to specify it.

有没有其他的选择吗?

谢谢!

推荐答案

试试这个:

public class CamelCasingFilterAttribute : ActionFilterAttribute
{
    private static JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter();

    static CamelCasingFilterAttribute()
    {
        _camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
        if (content != null)
        {
            if (content.Formatter is JsonMediaTypeFormatter)
            {
                actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, _camelCasingFormatter);
            }
        }
    }
}

应用此[CamelCasingFilter]属性要驼峰任何行动。它会带你正要发回并将其转换为使用camel大小写的属性名称,而不是任何JSON响应。

Apply this [CamelCasingFilter] attribute to any action you want to camel-case. It will take any JSON response you were about to send back and convert it to use camel casing for the property names instead.

这篇关于只能使用特定动作骆驼系列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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