Search code examples
c#asp.net-web-apiasp.net-mvc-5json.netsnakecase

Forcing SnakeCaseNamingStrategy doesn't work in ASP.NET MVC


I'm trying to force both serialization and deserialization to use SnakeCaseNamingStrategy but no luck.

Here is what I have used in Global.asax.cs:

protected void Application_Start() {
  AreaRegistration.RegisterAllAreas();
  GlobalConfiguration.Configure(WebApiConfig.Register);
  FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  RouteConfig.RegisterRoutes(RouteTable.Routes);
  BundleConfig.RegisterBundles(BundleTable.Bundles);

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

I even tried it like the following:

[JsonObject(NamingStrategyType = typeof(Newtonsoft.Json.Serialization.SnakeCaseNamingStrategy))]
public class RegisterBindingModel {
  [Required]
  [Display(Name = "Email")]
  public string Email { get; set; }

  [Required]
  [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
  [DataType(DataType.Password)]
  [Display(Name = "Password")]
  public string Password { get; set; }

  [DataType(DataType.Password)]
  [Display(Name = "Confirm password")]
  [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
  public string ConfirmPassword { get; set; }
}

Newtonsoft.Json version: 13.0.0.0

Update: the value for "ConfirmPassword" is always null when sending data with the key "confirm_password".


Solution

  • I have to confess that the problem was on my behalf and everything works as expected.

    I was sending text/plain to the API from Postman. And the other mistake was that I was expecting MVC controller to use JSON.NET as deserializer in ModelBinder which it doesn't use that so obviously it ignores my [JsonProperty()] annotations and even custom configurations in WebApiConfig.cs or Global.asax.cs.

    It should be noted that: Only ApiController uses JSON.NET as json serializer/deserializer in its ModelBinder.