WebApi下做项目配置

清疚 2023-10-07 11:22 130阅读 0赞
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Web;
  7. namespace YFAPICommon.Libs
  8. {
  9. public class MerchantConfig
  10. {
  11. public string Name { set; get; }
  12. public string MerchantID { set; get; }
  13. public string Pass { set; get; }
  14. }
  15. public class MerchantCache
  16. {
  17. private static Dictionary<string, MerchantConfig> merchantCache = null;
  18. private static string jsonfile = System.Web.Hosting.HostingEnvironment.MapPath(@"~/MerchantConfig.json");//JSON文件路径
  19. public static void initCache()
  20. {
  21. string jsonStr = System.IO.File.ReadAllText(jsonfile, Encoding.Default);
  22. merchantCache = JsonConvert.DeserializeObject<Dictionary<string,MerchantConfig>>(jsonStr);
  23. }
  24. public static MerchantConfig getMerchantConfig(string MerchantID)
  25. {
  26. if (merchantCache == null)
  27. initCache();
  28. MerchantConfig config = null;
  29. if (merchantCache.TryGetValue(MerchantID, out config))
  30. return config;
  31. else
  32. return null;
  33. }
  34. public static void clearCache()
  35. {
  36. merchantCache = null;
  37. }
  38. public static string addConfig(MerchantConfig input)
  39. {
  40. if (merchantCache == null)
  41. initCache();
  42. MerchantConfig config = null;
  43. if (merchantCache.TryGetValue(input.MerchantID, out config))
  44. {
  45. return "已存在不可添加";
  46. }
  47. else
  48. {
  49. merchantCache.Add(input.MerchantID,input);
  50. string jsonStr = JsonConvert.SerializeObject(merchantCache);
  51. System.IO.File.WriteAllText(jsonfile, jsonStr, Encoding.Default);
  52. return "添加成功";
  53. }
  54. }
  55. public static object getAllConfig()
  56. {
  57. if (merchantCache == null)
  58. initCache();
  59. return merchantCache;
  60. }
  61. }
  62. }
  63. {
  64. "333333": {
  65. "Name": "测试商户2",
  66. "MerchantID": "333333",
  67. "Pass": "xxxxxxxxxxxxxxx"
  68. },
  69. "1234567": {
  70. "Name": "测试商户",
  71. "MerchantID": "1234567",
  72. "Pass": "xxxxxxxxxxxxxxx"
  73. }
  74. }

发表评论

表情:
评论列表 (有 0 条评论,130人围观)

还没有评论,来说两句吧...

相关阅读