c#读取appsetting.json配置文件

asp.net core 取消了web.config配置文件,而将appsetting.json作为了配置文件。

那么,怎么读取相关数据呢?这里我在appsetting.json中添加一些信息

第一种:在.net core 类库中读取json文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Appsettings": {
    "ConnectionString": "Persist Security Info=True;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.17.202)(PORT=1032)))(CONNECT_DATA=(SERVICE_NAME = orcl)));User Id=ircs;Password=123456",
    "Port": 5000,
    "ReportDir": "C:\\Team2020\\ICRS\\ReportDir", //上报文件存放目录(未加密)
    "entityFilePath": "D:\\test", //监测日志实体文件存放目录
    "ircsId": "AB123", //经营者ID
    "level": "000001000000" //违法违网站处置规指令等级              
  },
  "AllowedHosts": "*"
}

这里我们需要添加netGet包:

注意:与读取Web.Config不同的是,asp.net 添加引用 using System.Configuration;

asp.net core 需要添加三个程序包,分别为:

Microsoft.Extensions.Configuration;
Microsoft.Extensions.Configuration.Abstractions;
Microsoft.Extensions.Configuration.Json;

加载配置文件的服务类:

    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();
        }

       
    }

获取数据:

var conStr = AppConfigurtaionServices.Configuration.GetSection("Appsettings:ConnectionString").Value;
var conStr2 = AppConfigurtaionServices.Configuration.GetSection("Appsettings").GetSection("ConnectionString").Value;

获取oracle数据库连接信息(两种写法都行):

第二种,控制器中获取json,(采用依赖注入的方式,注入获取配置文件的服务)

首先新建一个类,名称随意如:AppSettingModel

    /// <summary>
    /// 配置文件实体类
    /// </summary>
    public class AppSettingModel
    {
        public string ConnectionString { get; set; }
        public string Port { get; set; }
        public string ReportDir { get; set; }
        public string EntityFilePath { get; set; }
        public string IrcsId { get; set; }
        public string Level { get; set; }
    }

注意字段名要与配置文件的name一致。

在StartUp类的ConfigureServices 中加上:

//则是自动初始化AppSettings实例并且映射appSettings里的配置
services.Configure<AppSettingModel>(Configuration.GetSection("Appsettings"));

如果;IServiceCollection找不到,需要在NewGet添加   Microsoft.Extensions.DependencyInjection;

控制器获取相关数据:

public class AppSettingInfoController : Controller
    {
        public readonly AppSettingModel _appSettingModel;
//IOptions找不到,需要NuGet添加包 Microsoft.Extensions.Options;
public AppSettingInfoController(IOptions<AppSettingModel> appSettingModel) { _appSettingModel = appSettingModel.Value; } public ActionResult Index() { ViewData["conStr"] = _appSettingModel.ConnectionString; return null; }

猜你喜欢

转载自www.cnblogs.com/likui-bookHouse/p/11988057.html