zl程序教程

您现在的位置是:首页 >  工具

当前栏目

ABP 读取配置文件

2023-09-11 14:22:26 时间

原文:
https://www.cnblogs.com/lishidefengchen/p/10688312.html

需求

以前分部分项是从数据库里面查出来的,现在改为调用另一个项目的接口
赶时间就尽量微调,速度为主

百度找到了一篇文章,原以为可以白嫖的,结果我用的位置不一样,我是要在Application层读取配置,不是在web层读

主要参考的这里

1、定义接口和初始化

        private readonly IRepository<Project, int> _entityRepository;
        private readonly IHostingEnvironment _env;
        private readonly IConfigurationRoot _appConfiguration;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public ProjectAppService(
        IRepository<Project, int> entityRepository
            , IHostingEnvironment env
        )
        {
            _entityRepository = entityRepository;
            _env = env;
            _appConfiguration = GetAppConfiguration(env.ContentRootPath);
        }

        private IConfigurationRoot GetAppConfiguration(string path)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(path)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            builder = builder.AddEnvironmentVariables();

            return builder.Build();
        }

2、获取配置项里面的url地址

        //获取分部分项树2 for jstree by gxy 2020-2-28 16:08:13
        [Abp.Web.Models.DontWrapResult]
        public List<JsTreeResponseOutput2> GetProjectTrees2(string id)
        {
            //// 访问本地数据库
            //if (string.IsNullOrWhiteSpace(id) || (id == "#"))
            //{
            //    return GetTree();
            //    //return GetThreeRoot();
            //}
            //else
            //{
            //    return GetAllChildren(int.Parse(id));
            //}


            // 访问远程数据库-兰州中通道质量管理系统
            using (var httpClient = new HttpClient())
            {
                //var requestUri = "http://localhost:58059/SystemManage/Project/GetProjectsForBIMMP?id=" + id;
                var requestUri = _appConfiguration["SubSystem:ProjectUrl"] + "?id=" + id;

                var httpResponseMessage = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;
                var list = JsonConvert.DeserializeObject<List<JsTreeResponseOutput2>>(httpResponseMessage);
                return list;
            }
        }