Alexander Belenko Alexander Belenko - 1 year ago 142
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?

Answer Source

Found a solution:


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

To WebApiConfig.cs

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download