WebApi下做项目配置

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace YFAPICommon.Libs
{
    public class MerchantConfig
    {
        public string Name { set; get; }
        public string MerchantID { set; get; }
        public string Pass { set; get; }
        

    }
    public class MerchantCache
    {
        private static Dictionary<string, MerchantConfig> merchantCache = null;
        private static string jsonfile = System.Web.Hosting.HostingEnvironment.MapPath(@"~/MerchantConfig.json");//JSON文件路径
        public static void initCache()
        {
            
            string jsonStr = System.IO.File.ReadAllText(jsonfile, Encoding.Default);
            merchantCache = JsonConvert.DeserializeObject<Dictionary<string,MerchantConfig>>(jsonStr);
        }

        public static MerchantConfig getMerchantConfig(string MerchantID)
        {
            if (merchantCache == null)
                initCache();
            MerchantConfig config = null;
            if (merchantCache.TryGetValue(MerchantID, out config))
                return config;
            else
                return null;
        }

        public static void clearCache()
        {
            merchantCache = null;
        }

        public static string addConfig(MerchantConfig input)
        {
            if (merchantCache == null)
                initCache();

            MerchantConfig config = null;
            if (merchantCache.TryGetValue(input.MerchantID, out config))
            {
                return "已存在不可添加";
            }
            else
            {
                merchantCache.Add(input.MerchantID,input);
                string jsonStr = JsonConvert.SerializeObject(merchantCache);

                System.IO.File.WriteAllText(jsonfile, jsonStr, Encoding.Default);

                return "添加成功";
            }
        }

        public static object getAllConfig()
        {
            if (merchantCache == null)
                initCache();
            return merchantCache;
        }
    }
}
{
    "333333": {
        "Name": "测试商户2", 
        "MerchantID": "333333", 
        "Pass": "xxxxxxxxxxxxxxx"
    }, 
    "1234567": {
        "Name": "测试商户", 
        "MerchantID": "1234567", 
        "Pass": "xxxxxxxxxxxxxxx"
    }
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页