一、前言

在.Net Framework框架有专门获取webconfig配置的方法供我们使用,但是在.Net Core或者.Net Standard中没有可以直接使用的方法来获取配置文件信息,下面就来实现获取配置信息。

二、获取配置信息的实现

在.Net Core中,他的配置信息的载体是一个json文件,我们现在就计划所有项目(包含.Net Framework和.Net Standard(.Net Core)框架)都是json文件作为配置的载体。

首先通过Nuget加载如下的包:

Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.DependencyInjection
Install-Package Microsoft.Extensions.Options
Install-Package Microsoft.Extensions.Options.ConfigurationExtensions

现在我们使用json配置文件的内容有一下格式:

{
"ConnectionStrings": {
"CxyOrder": "Server=LAPTOP-AQUL6MDE\\MSSQLSERVERS;Database=CxyOrder;User ID=sa;Password=123456;Trusted_Connection=False;"
},
"Appsettings": {
"SystemName": "PDF .NET CORE",
"Date": "2017-07-23",
"Author": "PDF"
},
"ServiceUrl": "https://www.baidu.com/getnews"
}

创建PFTConfiguration.cs文件,代码如下:

 public class PFTConfiguration
{
/// <summary>
/// PFTConfiguration.Configuration.GetConnectionString("CxyOrder");
/// PFTConfiguration.Configuration["ServiceUrl"];
/// PFTConfiguration.Configuration["Appsettings:SystemName"];
/// </summary>
public static IConfiguration Configuration { get; set; }
static PFTConfiguration()
{
Configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
} /// <summary>
/// 获取配置信息
/// </summary>
/// <param name="path">json文件类型</param>
/// <typeparam name="T">返回实体类型</typeparam>
/// <param name="key">json关键字</param>
/// <returns></returns>
public static T GetAppsettings<T>(string key, string path) where T : class, new()
{
try
{
if (string.IsNullOrWhiteSpace(path))
{
throw new Exception("解析配置错误,配置文件路径为空");
}
if (string.IsNullOrWhiteSpace(key))
{
throw new Exception("解析配置错误,配置key为空");
}
var config = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.Add(new JsonConfigurationSource { Path = path, ReloadOnChange = true })
.Build();
var appconfig = new ServiceCollection()
.AddOptions()
.Configure<T>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
return appconfig;
}
catch (Exception ex)
{
throw new Exception("解析配置(对象)异常", ex);
} } /// <summary>
/// 获取配置信息
/// </summary>
/// <param name="key">json关键字</param>
/// <param name="path">json文件类型</param>
/// <returns></returns>
public static string GetAppsettings(string key, string path)
{
try
{
if (string.IsNullOrWhiteSpace(path))
{
throw new Exception("解析配置错误,配置文件路径为空");
}
if (string.IsNullOrWhiteSpace(key))
{
throw new Exception("解析配置错误,配置key为空");
}
var config = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.Add(new JsonConfigurationSource { Path = path, ReloadOnChange = true, Optional = false })
.Build();
var appconfig = config.GetSection(key).Value;
return appconfig;
}
catch (Exception ex)
{
throw new Exception("解析配置(字符串)异常", ex);
}
} }
}

里面定义了3种获取方法

1、PFTConfiguration.Configuration["Appsettings:SystemName"] 文件路径默认为appsettings.json,然后通过节点来获取,这个方式有点类似于.Net Framework中获取配置的方法

2、PFTConfiguration.GetAppsettings<T>(string key, string path),他是获取指定配置文件,指定节点,以T对象的形式返回节点内容

3、PFTConfiguration.GetAppsettings(string key, string path),他是获取指定配置文件,指定节点,以字符串的形式返回节点内容

.Net Standard(.Net Core)实现获取配置信息的更多相关文章

  1. .net core 2.0 mvc 获取配置信息

    mvc_core_config *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 ...

  2. AspNet Core 程序写入配置信息并再次读取配置信息

    1.首先创见Core控制台应用程序  并且引入  AspNetCore.All 首先我们写入配置信息:直接代码如下 //配置信息的根对象 public static IConfigurationRoo ...

  3. JavaWeb学习之Servlet(四)----ServletConfig获取配置信息、ServletContext的应用

    [声明] 欢迎转载,但请保留文章原始出处→_→ 文章来源:http://www.cnblogs.com/smyhvae/p/4140877.html [正文] 一.ServletConfig:代表当前 ...

  4. (转)JavaWeb学习之Servlet(四)----ServletConfig获取配置信息、ServletContext的应用

    [声明] 欢迎转载,但请保留文章原始出处→_→ 文章来源:http://www.cnblogs.com/smyhvae/p/4140877.html [正文] 一.ServletConfig:代表当前 ...

  5. Servlet生命周期 Servlet获取配置信息 ServletContext

    一.Servlet生命周期 实例化 ——> 初始化 ——>  服务 ——>  销毁 出生:(实例化 然后 初始化)tomcat第一次访问,Servlet就出生(默认情况下) 活着:( ...

  6. Asp.net Core Startup Class中是如何获取配置信息的

    默认的网站构建方式 VS2015新建asp.net core项目,项目建立完成后,有两个文件,Program.cs和Startup.cs. public class Program { public ...

  7. Servlet获取配置信息(ServletConfig)

    ServletConfig ServletConfig:当Servlet容器初始化Servlet时,Servlet容器会给Servlet的init方法传入一个ServletConfig.Servlet ...

  8. JavaWeb学习记录(八)——servlet获取配置信息

    jdbc.properties内容如下: jdbcUrl=jdbc\:mysql\://localhost\:3306/animaluser=rootpass=root servlet获取资源信息代码 ...

  9. python 模块 wmi 远程连接 windows 获取配置信息

    测试工具应用: https://ask.csdn.net/questions/247013 wmi连接不上报错问题集 https://blog.csdn.net/xcntime/article/det ...

随机推荐

  1. Sqlserver 锁表查询代码记录

    --方法1WITH CTE_SID ( BSID, SID, sql_handle ) AS ( SELECT blocking_session_id , session_id , sql_handl ...

  2. 使用sc 命令写脚本 添加和删除服务 简单应用

    添加服务 @echo.服务启动...... @echo off @sc create 服务名 binPath= "%~dp0\服务路径" @sc config 服务名 start= ...

  3. Git 实用技巧:git stash

    我们经常会遇到这样的情况: 正在dev分支开发新功能,做到一半时有人过来反馈一个bug,让马上解决,但是新功能做到了一半你又不想提交,这时就可以使用git stash命令先把当前进度保存起来.然后切换 ...

  4. notepad 写html乱码,已解决

    写一些简单基础的html文件时,突然发现新建的demo2,在浏览器打开乱码,而昨天的demo1打开没乱码,真奇怪,开始排查原因. 1.检查代码,,设了charset=UTF-8,看不出毛病. 2.索性 ...

  5. hive explode 行拆列

    创建一张表test_explode,表结构如下 表数据如下: 1.使用explode函数 select explode(friends) as friend from test_explode; 但是 ...

  6. 10G的变态SQL文件,如何快速打开编辑?

    工作中,偶尔需要编辑一些大文件,比如 log 文件,后者一些变态的 SQL,此时用平常的编辑器就会显得力不从心,要么直接打不开,要么打开后卡得要死. 本文就给大家推荐几款可以操作大文件的编辑器,准备好 ...

  7. CSS布局:元素水平垂直居中

    CSS布局:元素水平垂直居中 本文将依次介绍在不同条件下实现水平垂直居中的多种方法 水平垂直居中是在写网页时经常会用到的需求,在上两篇博客中,分别介绍了水平居中和垂直居中的方法.本文的水平垂直居中就是 ...

  8. Jmeter发送post请求报错Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

    常识普及: Content-type,在Request Headers里面,告诉服务器,我们发送的请求信息格式,在JMeter中,信息头存储在信息头管理器中,所以在做接口测试的时候,我们维护Conte ...

  9. Leetcode之深度优先搜索(DFS)专题-301. 删除无效的括号(Remove Invalid Parentheses)

    Leetcode之深度优先搜索(DFS)专题-301. 删除无效的括号(Remove Invalid Parentheses) 删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果. 说明 ...

  10. 怎样使用U盘安装Windows系统

    准备工作 一个8G及以上的U盘: 软碟通UltraISO,下载地址,非免费,但试用就够了: 系统镜像,推荐去MSDN下载: 安装过程 利用U盘制作启动盘,准备好上述的东西,然后开始制作启动盘: 注意: ...