appsetting.json内容
//省略部分代码... //代码生成相关 "CodeCreatorInfo": { "xmlPath": "11111", //xml路径(绝对路径) "jsRootPaht": "2222", //js文件夹路径 "Controllers": "333", //特殊Controller列表,逗号隔开 "NameSpace": "4444" //有效命名空间:"App.Web."之后的内容,主要用于多项目的项目,以逗号分隔,例如:APIControllers1,APIControllers2 } //省略部分代码...
方法一:控制器中获取json,采用依赖注入的方式
1、引用库using Microsoft.Extensions.Configuration;
2、使用接口服务:IConfiguration
注:观察这个类,这已经被 CodeCreatorController 自动注入了,无需手动做注入操作
using Microsoft.Extensions.Configuration; namespace App.Web.APIControllers { /// <summary> /// js代码生成接口 /// </summary> [Route("api/[controller]/[action]")] [ApiController] public class CodeCreatorController : BaseAPIController1 { /// <summary> /// 自动注入 /// </summary> /// <param name="configuration"></param> public CodeCreatorController(IConfiguration configuration) { _configuration = configuration; } public IConfiguration _configuration { get; } /// <summary> /// 获取XML文档内容,生成js文件内容,生成两种,分别用于页面和小程序 /// </summary> [HttpGet] public JsonResult CreateJsByXML() { //获取appsettiong配置内容 var CodeCreatorInfo = _configuration.GetSection("CodeCreatorInfo"); string xmlPath = _configuration.GetSection("CodeCreatorInfo")["xmlPath"]; /* 省略部分代码 */ } } }
注意:如果项目中需要用到反射,此时对应当前 Controller 的反射时会出错。可以使用方法二
方法二:在.net core 类库中读取json文件
1、添加引用:using System.Configuration; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json;
2、加载配置文件的服务类:
/// <summary> /// 获取appsetting的服务类 /// </summary> public class AppConfigurtaionServices { public static IConfiguration Configuration { get; set; } static AppConfigurtaionServices() { //ReloadOnChange = true 当appsettings.json被修改时重新加载 Configuration = new ConfigurationBuilder() //.SetBasePath(Directory.GetCurrentDirectory()) //AppDomain.CurrentDomain.BaseDirectory是程序集基目录,所以appsettings.json,需要复制一份放在程序集目录下, .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) .Build(); } }
3、获取数据:
/*省略部分代码*/ //类库中读取:两种取值方式【OK】 var xmlPath = AppConfigurtaionServices.Configuration.GetSection("CodeCreatorInfo:xmlPath").Value; var jsRootPaht = AppConfigurtaionServices.Configuration.GetSection("CodeCreatorInfo").GetSection("jsRootPaht").Value; var Controllers = AppConfigurtaionServices.Configuration.GetSection("CodeCreatorInfo").GetSection("Controllers").Value; var NameSpace = AppConfigurtaionServices.Configuration.GetSection("CodeCreatorInfo").GetSection("NameSpace").Value; var ControllersArray = Controllers.Split(','); var NameSpaceArray = NameSpace.Split(','); /*省略部分代码*/
原文:https://www.cnblogs.com/dyhao/p/13065774.html
标签:core,GetSection,配置文件,CodeCreatorInfo,appsetting,json,var,Configuration,public From: https://www.cnblogs.com/youmingkuang/p/18281584