返回带有小写首字母属性名称的json

我有LoginModel:

public class LoginModel : IData { public string Email { get; set; } public string Password { get; set; } } 

我有Web api方法

 public IHttpActionResult Login([FromBody] LoginModel model) { return this.Ok(model); } 

它返回200和身体:

 { Email: "dfdf", Password: "dsfsdf" } 

但是我希望能够获得较低的首字母属性

 { email: "dfdf", password: "dsfsdf" } 

我有Json合同解析器进行纠正

 public class FirstLowerContractResolver : DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { if (string.IsNullOrWhiteSpace(propertyName)) return string.Empty; return $"{char.ToLower(propertyName[0])}{propertyName.Substring(1)}"; } } 

我怎么能申请这个?

为了强制从api返回的所有json数据到camel case,使用默认的camel case合约解析器更容易使用Newtonsoft Json。

创建一个这样的类:

 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 formatters) { return new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json")); } } 

并在api配置期间(启动时)设置此项:

 var jsonFormatter = new JsonMediaTypeFormatter(); httpConfiguration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); 

如果您使用的是Newtonsoft.Json ,则可以将JsonProperties添加到视图模型中:

 public class LoginModel : IData { [JsonProperty(PropertyName = "email")] public string Email {get;set;} [JsonProperty(PropertyName = "password")] public string Password {get;set;} } 

您可以在Web API配置或启动文件中添加以下两个语句

 使用Newtonsoft.Json;
使用Newtonsoft.Json.Serialization;

 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;

但是使用return Ok()方法而不是return Json() 非常重要否则这将无效。