Alexander Belenko Alexander Belenko - 9 months ago 71
JSON Question

How to set json format in ResponseType attribute ( webapi)?

My controller's actions return IHttpActionResult. In project I use snake_case as json format so I add custom ContractResolver to json settings:

JsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new SnakeCasePropertyNamesContractResolver() };

And that's how I format response:

return new JsonResult<UserInfoModel>(new UserInfoModel(user.UserInfo), JsonSerializerSettings, Encoding.Unicode, this);

For autogenerated documentation I add [ResponseType] attribute to methods. But documentation use camelCase format for response exmaples.

How to set json format in ResponseType attribute?


Found a solution:


var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new SnakeCasePropertyNamesContractResolver();
config.Formatters.Add(new JsonMediaTypeFormatter());

To WebApiConfig.cs