在每个控制器的WebAPI上强制SnakeCase反序列化

时间:2017-11-25 10:00:57

标签: c# asp.net-web-api serialization json.net asp.net-web-api2

我想为我的一个控制器更改传入请求反序列化格式。所以我把它添加到我的Global.asax中,它运作得很好:

HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver
    {
        NamingStrategy = new SnakeCaseNamingStrategy()
    }
};

但它将更改应用于所有控制器。我只想将它应用于我的一个控制器。我还找到this回答,我根据这个编写了这段代码:

public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
    var formatter = controllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single();
    controllerSettings.Formatters.Remove(formatter);

    formatter = new JsonMediaTypeFormatter
    {
        SerializerSettings = { ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() } }
    };

    controllerSettings.Formatters.Add(formatter);
}

但不幸的是它仅用于序列化输出。有没有办法定义它来反序列化输入?

0 个答案:

没有答案