Replacekeywords.cs 6.9 KB
using Model;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Http = Model.Http;

namespace BLL
{
    //请求处理关键字
    public class Replacekeywords
    {
        public static string Replacekeywordss(Dictionary<string, string> macroKey)
        {
            string jsondata = null;
            Config config = new Config();
            #region 验证配置数据是否正确
            //未找到任何ns100设置的关键字信息
            if (macroKey == null || macroKey.Count < 0)
            {
                LogNet.log.Error("更换关键字:未找到任何关键字信息,请重新设置!");
                throw new Exception("未找到任何关键字信息,请重新设置!");
            }
            if (config.Method != Method.POST && config.Method != Method.GET)
            {
                LogNet.log.Error("更换关键字:请求方式参数不正确!");
                throw new Exception("请求方式参数不正确!");
            }
            if (config.IsTokenRequired && config.Tokenurl == null)
            {

                LogNet.log.Error("更换关键字:需要请求token,请填写tokenurl!");
                throw new Exception("需要请求token,请填写tokenurl!");
            }
            if (string.IsNullOrWhiteSpace(config.Url) || config.KeyWords.Length < 0)
            {
                LogNet.log.Error("更换关键字:URL和关键字不能为空");
                throw new Exception("URL和关键字不能为空");
            }
            config.filteredData = macroKey
                          .Where(kvp => config.KeyWords.Contains(kvp.Key))
                          .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            //判断结果中是否包含指定关键字
            bool allinkey = config.filteredData.Count > 0; /*== config.KeyWords.Count();*/
            if (!allinkey)
            {

                LogNet.log.Error($"更换关键字:关键字未包含;{config.KeyWords}");
                throw new Exception($"关键字未包含;{config.KeyWords}");
            }
            #endregion

            #region 根据请求方式,设置请求数据  
            // 创建一个请求
            var request = new RestRequest(config.Method);
            // 需要token
            if (config.IsTokenRequired)
            {
                string responseJson = Http.GetToken(config.Tokenurl);
                // 解析 JSON
                JObject jsonObject = JObject.Parse(responseJson);
                // 提取 Token 的值
                string tokenValue = (string)jsonObject["Token"];
                request.AddHeader("Authorization", tokenValue);
                LogNet.log.Error($"更换关键字:请求token:{tokenValue}");
            }
            jsondata = SendHttpRequest(config, request);
            if (string.IsNullOrWhiteSpace(jsondata))
            {
                throw new Exception("返回信息为空请检查请求!");
            }
            #endregion
            return jsondata;
        }
        public static string SendHttpRequest(Config config, RestRequest request)
        {
            string json = "";
            if (request.Method == Method.GET)
            {
                List<string> parstringParts = new List<string>();

                foreach (var item in config.KeyWords) // 客户指定的关键字
                {
                    // 尝试从识别出来的关键字数据中获取值
                    if (config.filteredData.TryGetValue(item, out var value))
                    {
                        parstringParts.Add(value);
                    }
                    else
                    {
                        // 如果未找到值,则使用关键字的分割后数据
                        string[] parts = item.Split('=');
                        if (parts.Length > 1)
                        {
                            parstringParts.Add(parts[1]);
                        }
                    }
                }
                string parstring = string.Join(",", parstringParts);
                //parstring = "Y023070966,WPG0001,1,infobar";
                config.Url += $"&customloadmethodparms={parstring}&loadtype=NEXT&readonly=true&rowcap=-1";
                var client = new RestClient(config.Url);
                LogNet.log.Error($"更换关键字:请求Url:{config.Url}");
                // 禁用自动重定向
                client.FollowRedirects = false;
                var response = client.Execute(request);
                if ((int)response.StatusCode >= 300 && (int)response.StatusCode < 400)
                {
                    // 获取重定向后的新 URL
                    string newUrl = response.Headers.FirstOrDefault(header => header.Name.Equals("Location", StringComparison.OrdinalIgnoreCase))?.Value.ToString();
                    // 创建一个新的 RestClient 实例,用于新的 URL
                    var newClient = new RestClient(newUrl);
                    // 发送请求到新的 URL
                    var newResponse = newClient.Execute(request);
                    json = newResponse.Content;
                }
                else
                {
                    json = response.Content;
                }
            }
            LogNet.log.Error($"更换关键字:{json}");
            return json;
        }
        public class Config
        {
            //是否需要请求token           
            public Method Method { get; set; } = ConfigHelper.Config.Get("SelectHttpPN_RequestMethod", "GET") == "POST" ? Method.POST : Method.GET;
            //是否需要请求token           
            public string ContentType { get; set; } = ConfigHelper.Config.Get("SelectHttpPN_ContentType", "application/json");
            //是否需要请求token           
            public bool IsTokenRequired { get; set; } = ConfigHelper.Config.Get("SelectHttpPN_IsTokenRequired", true);
            //请求tokenurl
            public string Tokenurl { get; set; } = ConfigHelper.Config.Get("SelectHttpPN_Tokenurl", "");
            //请求正常数据
            public string Url { get; set; } = ConfigHelper.Config.Get("SelectHttpPN_Url", "");
            //关键字,请用,号分割
            public string[] KeyWords { get; set; } = ConfigHelper.Config.Get("SelectHttpPN_KeyWords", "").Split(',');

            /// <summary>
            /// 此字段在需要存放,请求数据的键值对
            /// </summary>
            public Dictionary<string, string> filteredData { get; set; }
        }
        public class ResponseItem
        {
            public string Name { get; set; }
            public string Value { get; set; }
        }
        public class ResponseDatas
        {
            public List<List<ResponseItem>> Items { get; set; }
            public string Message { get; set; }
            public int MessageCode { get; set; }
        }
    }
}