.NET Core 获取自定义配置文件信息(多种方式)

news/2024/7/2 20:15:49

引用 Microsoft.AspNetCore.App 元包或将包引用添加到 Microsoft.Extensions.Options.ConfigurationExtensions 包。

简而言之,直接可以用:

Appsetting.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Setting": {
    "Url": "http://localhost:8080/",
    "LogPath": "D/ItemService"   
  },
  "AllowedHosts": "*"  
}


configuration["Setting:Url"]
configuration.GetValue<string>("Setting:Url")
configuration GetSection("Setting"). GetSection("Url")

 

方法二:

新建model类Settings

{
 Public string A{get;set;}
};

其中A对应与json中配置文件的key,这里类是

{
 Public string Url{get;set;}
 Public string LogPath{get;set;}
};

在Startup.cs中ConfigureServices的方法

services.Configure<Settings>(options =>
            {
                options.ConnectionString = configuration.GetSection("Setting:Url").Value;
                options.Database = configuration.GetSection("Setting:LogPath").Value;
            });

 

使用:这样可以在全局拿到配置文件

 public BController(IOptions<Settings> settings)
        {
            url=settings.Value.Url;
            logpath = settings.Value.LogPath);
        }

 


http://www.niftyadmin.cn/n/4353420.html

相关文章

.net core 集成mongoDB

NoSQL非关系型数据库支持CAP定理和最终一致性的特性&#xff0c;所以分布式系统中可以完美的结合&#xff0c;提高性能。 第一步&#xff1a; 新建项目 NuGet管理引入了 “MongoDB.Driver"&#xff1b;官方链接&#xff1a;http://mongodb.github.io/mongo-csharp-driv…

.net core 集成Redis

第一步&#xff1a; 引用StackExchange.Redis 第二步&#xff1a; 初始化 private string constr "127.0.0.1:6379,allowadmintrue"; connect ConnectionMultiplexer.Connect(constr);第三步&#xff1a; 获取数据库 dbconnect.GetDatabase(1);第四步&#xff…

线程安全、简单的单例编写

单例的特性&#xff1a;一、构造方法私有&#xff1b;二、 定义SingleInstance 类型属性 一、不安全的单例 public class SingleInstance {private static SingleInstanceinstance null;public static SingleInstance instance{get{if (instance null){instance new Single…

c# Task启动带参数和返回值的方法

Task启动带参数 Task.Run(() > test("123"));public void Test(string s){...todo.. } Task启动带参数和返回值的方法 var s Task.Run(() > isTest("ss"));var t s.Result;private bool isTest(string isno) {return true;}

Window Server IIS日志查看

安装Log Parser https://www.microsoft.com/en-us/download/details.aspx?id24659 打开log LogParser.exe -i:IISW3C -o:DATAGRID "SELECT c-ip,cs-method,s-port,cs-uri-stem,sc-status,sc-win32-status,sc-bytes,cs-bytes,time-taken FROM D:\Log\u_ex130615.log&qu…

Window Server IIS日志导入到SQL Server查看

配置ODBC log日志可以导出到提供ODBC访问接口的数据库查看 控制面板-ODBC 添加DSN->SQL Server 起个名称&#xff08;随意命名&#xff09; 下一步&#xff1a;选择数据库 下一步&#xff1a;默认就行 点完成 测试数据源 点击确定 点击应用-确定 打开logparser 输入&#…

Window Server IIS日志导入到SQL Server查看之时间转换

根据https://blog.csdn.net/yeluo_vinager/article/details/106147019 日志导入到SQLServer 以后时间是UTC格式 而且日期和时间分开了&#xff0c;导出到SQLSERVER时&#xff0c;会生成二个字段 把UTC时间换成本地时区的时间 有两个方式 一、SQL Server sql语句转换 alter…

Action和Func的使用

Action和Func两者的区别在于Action没有返回值&#xff0c;而Func有返回值。 在调用 Func<int,bool>XXX时,只需要传入一个int型参数即可&#xff0c;它将会返回一个bool类型的值。即Func尖括号内最后一个类型代表该Func的返回类型。