U9客开使用缓存保存token

2023/01/14

这篇文章发布于 483 天前,部分信息可能已经发生变化。

  • 需求背景:调用MES接口,需先获取Token,Token需要保存起来复用.

引用:System.Runtime.Caching.dll

MemoryCache 类 (System.Runtime.Caching) | Microsoft Learn - https://learn.microsoft.com/zh-cn/dotnet/api/system.runtime.caching.memorycache?view=netframework-4.5

  • 适用BE插件/BP
internal class Program
    {
        private static MemoryCache MemoryCache = new MemoryCache("MEStoken", null);
        static void Main(string[] args)
        {

            for (int i = 0; i < 5; i++)
            {

                string token = "";
                if (MemoryCache.Get("token") == null)
                {
                    var par1 = new Dictionary<string, object>();
                    par1.Add("UserName", "MESWeb01");
                    par1.Add("UserPassword", "MESWeb5d2G8J1");
                    token = Webapi.GetDataRequest(par1, "http://192.168.1.215:80/OrBitWCFServiceR15/OrBitWebAPI.ashx");
                    MemoryCache.Set("token", token, DateTimeOffset.Now.AddMinutes(500.0));
                }
                else
                {
                    token = MemoryCache.Get("token").ToString();
                }


                var par2 = new Dictionary<string, object>();
                par2.Add("OutType", "JSON");
                par2.Add("API", "MESIsApproved");
                par2.Add("UserTicket", token);

                var injosin = new InJSON();
                injosin.DOCType = "RMRHead";
                injosin.ERPID = "1002011101322941";
                string jsonstr = JsonConvert.SerializeObject(injosin);
                par2.Add("UserParameter", jsonstr);
                Webapi.GetDataRequest(par2, "http://192.168.1.215:80/OrBitWCFServiceR15/OrBitWebAPI.ashx");
            }

        }
    }