WebApi 返回小駝峰式 json 格式,並格式化日期
在 WebApiConfig 類中增加方法ConfigureApi,並在 Register 方法最後呼叫一下 ConfigureApi(config);
增加一個實現IContentNegotiator 介面的類 JsonContentNegotiator
詳細如下:
public static void ConfigureApi(HttpConfiguration config)
{var jsonFormatter = new JsonMediaTypeFormatter();
var settings = jsonFormatter.SerializerSettings;
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
//這裡使用自定義日期格式
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
settings.Converters.Add(timeConverter);
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
}
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}