Web API: Configure JSON serializer settings on action or controller level

ぃ、小莉子 提交于 2019-12-28 03:45:09

问题


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:


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

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



回答2:


Here's an implementation of the above as Action Attribute:

public class CustomActionJsonFormatAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext?.Response == null) return;

        var content = actionExecutedContext.Response.Content as ObjectContent;

        if (content?.Formatter is JsonMediaTypeFormatter)
        {
            var formatter = new JsonMediaTypeFormatter
            {
                SerializerSettings =
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }
            };

            actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, formatter);
        }
    }
}

public class MyController : ApiController
{
    [CustomActionJsonFormat]
    public IHttpActionResult Get()
    {
        var model = new MyModel();
        return Ok(model);
    }
}


来源:https://stackoverflow.com/questions/44499041/web-api-configure-json-serializer-settings-on-action-or-controller-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!