在全局设置webapi设置json返回类型首字母小写:config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
但是想针对个别api设置默认的json格式,怎么办呢?
下面是一种方案:
第一步:自定义一个消息处理程序
/// <summary> /// 自定义http消息处理程序 /// </summary> public class MessageHandlerOne : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request.RequestUri.AbsolutePath.Contains("api地址中使用默认的标识"))//如api/ddd request.GetConfiguration().Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver(); else request.GetConfiguration().Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); return base.SendAsync(request, cancellationToken); } }
第二步:将自定义消息处理程序加的GlobalConfiguration中
GlobalConfiguration.Configure(config =>
{
config.MessageHandlers.Add(new MessageHandlerOne());
});
来源:https://www.cnblogs.com/Jenny-1/p/12332277.html