ResultHelper.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Business.StructuredDB
  8. {
  9. public class ResultHelper
  10. {
  11. public static ResultViewModel CreateResult(int row, string msg)
  12. {
  13. ResultCode code = ResultCode.Fail, subCode = ResultCode.BusinessError;
  14. if (row > 0)
  15. {
  16. code = ResultCode.Success;
  17. }
  18. else
  19. {
  20. if (msg == "")
  21. {
  22. subCode = ResultCode.ExistsError;
  23. }
  24. }
  25. return CreateResult(code, null, subCode, msg);
  26. }
  27. public static ResultViewModel CreateResult(ResultCode code = ResultCode.Fail, dynamic data = null, ResultCode subCode = ResultCode.Fail, string subMsg = "")
  28. {
  29. string Msg = GetCustomAttributes(code);
  30. if (code == ResultCode.Success)
  31. {
  32. subCode = code;
  33. subMsg = string.IsNullOrEmpty(subMsg) ? Msg : subMsg;
  34. }
  35. else
  36. {
  37. subMsg = string.IsNullOrEmpty(subMsg) ? GetCustomAttributes(subCode) : subMsg;
  38. }
  39. return new ResultViewModel()
  40. {
  41. Code = Convert.ToInt32(code).ToString(),
  42. Msg = Msg,
  43. SubCode = Convert.ToInt32(subCode).ToString(),
  44. SubMsg = subMsg,
  45. Data = data
  46. };
  47. }
  48. private static string GetCustomAttributes(ResultCode code)
  49. {
  50. Type type = code.GetType();
  51. FieldInfo fieldInfo = type.GetField(code.ToString());
  52. var customAttributes = fieldInfo.GetCustomAttributesData();
  53. if (customAttributes.Count > 0)
  54. {
  55. return customAttributes[0].NamedArguments[0].TypedValue.Value.ToString();
  56. }
  57. return "";
  58. }
  59. }
  60. }