Alexander Belenko Alexander Belenko - 3 months ago 27
JSON Question

How to set json format in ResponseType attribute (asp.net 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

Found a solution:

Add

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

To WebApiConfig.cs

Comments