WebApi返回Json格式
一、Global配置(此方法杀伤力太大,所有的返回的xml格式都会被毙掉)
public class WebApiApplication : System.Web.HttpApplication{
protected void Application_Start(){
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); //<------- 毙掉XML使api返回为json
}
}
但有个不好的地方,如果返回的结果是String类型,如aaa,返回的json就会变成"aaa"
二、WebApiConfig配置
namespace TestWebApi{
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Web API 配置和服务
#region [=>1、WebApi 返回JSON,不推荐做法性能不高]
/*
config.Formatters.Clear();
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings{
ContractResolver = new UnderlineSplitContractResolver(), //小写命名法。
DateFormatString = "yyyy-MM-dd HH:mm:ss",//解决json时间带T的问题
Formatting = Newtonsoft.Json.Formatting.Indented,//解决json格式化缩进问题
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore//解决json序列化时的循环引用问题
};
*/
#endregion
#region [=>2、WebApi 返回JSON,推荐做法性能最高]
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(new JsonMediaTypeFormatter()));
#endregion
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
/// <summary>
/// 在全局设置中,使用自定义的只返回Json Result。只让api接口中替换xml,返回json。这种方法的性能是最高的!
/// </summary>
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
// 对 JSON 数据使用混合大小写。驼峰式,但是是javascript 首字母小写形式.小驼峰命名法。
//config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// 对 JSON 数据使用混合大小写。跟属性名同样的大小.输出
_jsonFormatter.SerializerSettings.ContractResolver = new UnderlineSplitContractResolver(); //小写命名法。
_jsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//解决json时间带T的问题
_jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;//解决json格式化缩进问题
_jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;//解决json序列化时的循环引用问题
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}
/// <summary>
/// Json.NET 利用ContractResolver解决命名不一致问题
/// 解决问题:通过无论是序列化还是反序列化都达到了效果,即:ProjectName -> project_name 和 project_name -> ProjectName
/// </summary>
public class UnderlineSplitContractResolver : DefaultContractResolver {
protected override string ResolvePropertyName(string propertyName) {
return CamelCaseToUnderlineSplit(propertyName);//下划线分割命名法
//return propertyName.ToLower();//小写命名法
}
private string CamelCaseToUnderlineSplit(string name) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < name.Length; i++) {
var ch = name[i];
if (char.IsUpper(ch) && i > 0) {
var prev = name[i - 1];
if (prev != '_'){
if (char.IsUpper(prev)){
if (i < name.Length - 1){
var next = name[i + 1];
if (char.IsLower(next)) {
builder.Append('_');
}
}
} else {
builder.Append('_');
}
}
}
builder.Append(char.ToLower(ch));
}
return builder.ToString();
}
}
}