use camel case serialization only for specific actions

后端 未结 1 1933
耶瑟儿~
耶瑟儿~ 2020-12-10 12:54

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.

Recently however

1条回答
  •  执笔经年
    2020-12-10 13:53

    Try this:

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

    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.

    0 讨论(0)
提交回复
热议问题