Return json with lower case first letter of property names
If your are using Newtonsoft.Json, you can add JsonProperties to your view model :
public class LoginModel : IData
{
[JsonProperty(PropertyName = "email")]
public string Email {get;set;}
[JsonProperty(PropertyName = "password")]
public string Password {get;set;}
}
To force all json data returned from api to camel case it's easier to use Newtonsoft Json with the default camel case contract resolver.
Create a class like this one:
using Newtonsoft.Json.Serialization;
internal class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
_jsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
return new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
}
}
and set this during api configuration (at startup):
var jsonFormatter = new JsonMediaTypeFormatter();
httpConfiguration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
You can add the two following statement in the configuration of the web API or to the startup file
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
But it is very important to use the return Ok()
method instead of return Json()
otherwise; this will not work.
if you have to use Json method (and have no other choice) then see this answer https://stackoverflow.com/a/28960505/4390133