鼎鼎知识库
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

2020.12.1后端接口格式实现.md 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. > 正常响应
  2. ```
  3. {
  4. "version": "1.0.0.0",
  5. "code": 200,
  6. "message": "this is message",
  7. "isError": false,
  8. "data": {
  9. "id": 1,
  10. "name": "name",
  11. "age": 21
  12. }
  13. }
  14. ================================
  15. 使用ApiResponse构造函数返回正常响应。
  16. [Route("get1")]
  17. [HttpGet]
  18. public ApiResponse Get1()
  19. {
  20. var data = new { Id = 1, Name = "name", Age = 21 };
  21. return new ApiResponse("this is message", data, StatusCodes.Status200OK);
  22. }
  23. ```
  24. > 异常响应
  25. ```
  26. {
  27. "version": "1.0.0.0",
  28. "code": 500,
  29. "isError": true,
  30. "responseException": {
  31. "exceptionMessage": "Unhandled Exception occurred. Unable to process the request."
  32. }
  33. }
  34. ================================
  35. 在接口层throw抛出异常
  36. [Route("get1")]
  37. [HttpGet]
  38. public ApiResponse Get1()
  39. {
  40. try
  41. {
  42. int i = 0;
  43. int j = 5 / i;
  44. return new ApiResponse("New record has been created in the database", 1, StatusCodes.Status201Created);
  45. }
  46. catch (Exception ex)
  47. {
  48. throw;
  49. }
  50. }
  51. ==============================
  52. 使用ApiException抛出特定类型的异常。
  53. [HttpGet]
  54. [Route("get2")]
  55. public ApiResponse Get2()
  56. {
  57. throw new ApiException("doesnt exist", StatusCodes.Status404NotFound);
  58. }
  59. ```
  60. > 入参字段不符合要求响应
  61. ```
  62. {
  63. "version": "1.0.0.0",
  64. "code": 400,
  65. "isError": true,
  66. "responseException": {
  67. "exceptionMessage": "Request responded with one or more validation errors occurred.",
  68. "validationErrors": [
  69. {
  70. "name": "Name",
  71. "reason": "最大长度5"
  72. },
  73. {
  74. "name": "Location",
  75. "reason": "最大长度5"
  76. }
  77. ]
  78. }
  79. }
  80. ================================
  81. 使用ApiException抛模型错误异常。
  82. [HttpPost]
  83. [Route("customException")]
  84. public ApiResponse Post1(AutoWrapperDemo model)
  85. {
  86. if(!ModelState.IsValid)
  87. {
  88. throw new ApiException(ModelState.AllErrors());
  89. }
  90. return new ApiResponse("New record has been created in the database", 1, StatusCodes.Status201Created);
  91. }
  92. ```