Return json with lower case first letter of property names

前端 未结 4 1925
走了就别回头了
走了就别回头了 2021-02-01 17:43

I have LoginModel:

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

and I hav

4条回答
  •  离开以前
    2021-02-01 18:01

    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 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));
    

提交回复
热议问题