仅针对特定操作使用camel case序列化

Fra*_*ard 11 asp.net-web-api

我已经使用了一段时间的WebAPI,并且通常将其设置为使用驼峰式json序列化,这现在相当普遍并且在各处都有详细记录.

然而,最近,在一个更大的项目上工作,我遇到了一个更具体的要求:我们需要使用camel case json序列化,但由于我们的客户端脚本的向后兼容性问题,我只希望它发生在特定的操作上,以避免打破(非常大)网站的其他部分.

我认为一个选项是拥有自定义内容类型,但那需要客户端代码来指定它.

还有其他选择吗?

谢谢!

You*_*oui 28

试试这个:

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

    public 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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将此[CamelCasingFilter]属性应用于您想要camel-case的任何操作.它将需要您发回的任何JSON响应并将其转换为使用驼峰套管来代替属性名称.

  • 得到它:`JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();` (2认同)