当前位置:   article > 正文

【WebAPI】返回JSON数据_webapi返回json数据

webapi返回json数据

Global.asax文件WebApiApplication中配置

  1. public class WebApiApplication : System.Web.HttpApplication
  2. {
  3. protected void Application_Start()
  4. {
  5. AreaRegistration.RegisterAllAreas();
  6. GlobalConfiguration.Configure(WebApiConfig.Register);
  7. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  8. RouteConfig.RegisterRoutes(RouteTable.Routes);
  9. BundleConfig.RegisterBundles(BundleTable.Bundles);
  10. //返回json数据
  11. GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
  12. }
  13. }

在WebApiConfig中配置

  1. public static class WebApiConfig
  2. {
  3. public static void Register(HttpConfiguration config)
  4. {
  5. // Web API 配置和服务
  6. config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(new JsonMediaTypeFormatter()));
  7. // Web API 路由
  8. config.MapHttpAttributeRoutes();
  9. config.Routes.MapHttpRoute(
  10. name: "DefaultApi",
  11. routeTemplate: "api/{controller}/{id}",
  12. defaults: new { id = RouteParameter.Optional }
  13. );
  14. }
  15. /// <summary>
  16. /// 在全局设置中,使用自定义的只返回Json Result。只让api接口中替换xml,返回json。这种方法的性能是最高的!
  17. /// </summary>
  18. public class JsonContentNegotiator : IContentNegotiator
  19. {
  20. private readonly JsonMediaTypeFormatter _jsonFormatter;
  21. public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
  22. {
  23. _jsonFormatter = formatter;
  24. }
  25. public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
  26. {
  27. // 对 JSON 数据使用混合大小写。驼峰式,但是是javascript 首字母小写形式.小驼峰命名法。
  28. //config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  29. // 对 JSON 数据使用混合大小写。跟属性名同样的大小.输出
  30. _jsonFormatter.SerializerSettings.ContractResolver = new UnderlineSplitContractResolver(); //小写命名法。
  31. _jsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//解决json时间带T的问题
  32. _jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;//解决json格式化缩进问题
  33. _jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;//解决json序列化时的循环引用问题
  34. var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
  35. return result;
  36. }
  37. }
  38. /// <summary>
  39. /// Json.NET 利用ContractResolver解决命名不一致问题
  40. /// 解决问题:通过无论是序列化还是反序列化都达到了效果,即:ProjectName -> project_name 和 project_name -> ProjectName
  41. /// </summary>
  42. public class UnderlineSplitContractResolver : DefaultContractResolver
  43. {
  44. protected override string ResolvePropertyName(string propertyName)
  45. {
  46. return CamelCaseToUnderlineSplit(propertyName);//下划线分割命名法
  47. //return propertyName.ToLower();//小写命名法
  48. }
  49. private string CamelCaseToUnderlineSplit(string name)
  50. {
  51. StringBuilder builder = new StringBuilder();
  52. for (int i = 0; i < name.Length; i++)
  53. {
  54. var ch = name[i];
  55. if (char.IsUpper(ch) && i > 0)
  56. {
  57. var prev = name[i - 1];
  58. if (prev != '_')
  59. {
  60. if (char.IsUpper(prev))
  61. {
  62. if (i < name.Length - 1)
  63. {
  64. var next = name[i + 1];
  65. if (char.IsLower(next))
  66. {
  67. builder.Append('_');
  68. }
  69. }
  70. }
  71. else
  72. {
  73. builder.Append('_');
  74. }
  75. }
  76. }
  77. builder.Append(char.ToLower(ch));
  78. }
  79. return builder.ToString();
  80. }
  81. }
  82. }

 

参考:

https://www.cnblogs.com/xinyibufang/p/10478137.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/550415
推荐阅读
相关标签
  

闽ICP备14008679号