当前位置:   article > 正文

ASP.NET Core 一个Json返回类

ASP.NET Core 一个Json返回类

很多时候(如Ajax)我们需要从Web应用中得到标准的反馈以便进行数据分析。

为此,我将各类返回标准化封装,客户端将统一得到 JSON:[{"status":200,"message":"success","data":[Object]}],有利于建立统一的数据处理模型。

  1. public class ReturnStd
  2. {
  3. public class ReturnJson
  4. {
  5. public string Status { get; set; }
  6. public string Message { get; set; }
  7. public object Data { get; set; }
  8. }
  9. public static ReturnJson ComJson(string responseMessage, string responseCode, object rtnData = null)
  10. {
  11. ReturnJson returnJson = new ReturnJson()
  12. {
  13. Status = responseCode,
  14. Message = responseMessage,
  15. Data = rtnData ?? string.Empty
  16. };
  17. return returnJson;
  18. }
  19. public static ReturnJson Success(object rtnData = null)
  20. {
  21. ReturnJson returnJson = new ReturnJson()
  22. {
  23. Status = "200",
  24. Message = string.Empty,
  25. Data = rtnData?? string.Empty
  26. };
  27. return returnJson;
  28. }
  29. public static ReturnJson Error(string responseMessage, string responseCode = "400", object rtnData = null)
  30. {
  31. ReturnJson returnJson = new ReturnJson()
  32. {
  33. Status = responseCode,
  34. Message = responseMessage ?? string.Empty,
  35. Data = rtnData ?? string.Empty
  36. };
  37. return returnJson;
  38. }
  39. public static ReturnJson ModelError(ModelStateDictionary modelState, string responseCode = "400", object rtnData = null)
  40. {
  41. string messages = string.Join("; ", modelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
  42. ReturnJson returnJson = new ReturnJson()
  43. {
  44. Status = responseCode,
  45. Message = messages,
  46. Data = rtnData ?? string.Empty
  47. };
  48. return returnJson;
  49. }
  50. public static ReturnJson NotAuthorize(string responseMessage, string responseCode = "90", object rtnData = null)
  51. {
  52. ReturnJson returnJson = new ReturnJson()
  53. {
  54. Status = responseCode,
  55. Message = responseMessage ?? string.Empty,
  56. Data = rtnData ?? string.Empty
  57. };
  58. return returnJson;
  59. }
  60. }

  如何使用?

  1. [HttpGet]
  2. public JsonResult GetUsers(long lastUpdateTicks=0)
  3. {
  4. List<SYS_User_OnCloud> rtnData = _context.SYS_User_OnClouds.Where(u => ((long?)u.LastUpdateTicks?? 0) >= lastUpdateTicks).ToList();
  5. return Json(ReturnStd.Success(rtnData));
  6. }

  

转载于:https://www.cnblogs.com/imes/p/9801201.html

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

闽ICP备14008679号