系列目录

循序渐进学.Net Core Web Api开发系列目录

本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi

一、本篇概述

本篇描述appsettings.json的使用,包括:

1、配置的基本读取

2、读取配置信息到自定义的对象

3、自定义配置文件

一、配置的基本读取

要读取的配置文件内容如下:

{
"ConnString": "MySQL Connect String",
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"SystemConfig": {
"UploadFile": "d:\\files",
"AnnexUrl": "http://192.168.0.177:81/",
"Admin": {
"Name": "admin",
"Age": "",
"Allow": "True"
},
"DefaultPassword": ""
}
}

读取配置文件的方法如下:

   public class Startup
{
public Startup(IConfiguration configuration,IHostingEnvironment env)
{
Configuration = configuration;
_env = env;
} public IConfiguration Configuration { get; }
public IHostingEnvironment _env { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(); var ConnString = Configuration["ConnString"];
var UploadFile = Configuration.GetSection("SystemConfig")["UploadFile"];
var AdminName = Configuration.GetSection("SystemConfig").GetSection("Admin")["Name"];
}
}

还有一种读法:

            ConnString = Configuration["ConnString"];
UploadFile = Configuration["SystemConfig:UploadFile"];
AdminName = Configuration["SystemConfig:Admin:Name"];

这里Startup类在构造时已经帮我们注入了Configuration,如果要在自己的Controller内使用,需要自己注入。

    public class ValuesController : Controller
{
private IConfiguration _configuration; public ValuesController(IConfiguration configuration)
{
_configuration = configuration;
} [HttpGet]
public IEnumerable<string> Get()
{
var ConnString = _configuration["ConnString"];
return new string[] { "value1", "value2" };
}
}

二、读取配置信息到自定义的对象

新建一个类,用来存储配置信息,类的结构应和配置文件一致。

    public class SystemConfig
{
public String UploadFile { get; set; }
public String AnnexUrl { get; set; }
public User Admin { get; set; }
public String DefaultPassword { get; set; }
} public class User
{
public String Name { get; set; }
public int Age { get; set; }
public bool Allow { get; set; }
}

在startup类的ConfigureServices方法内,提供如下代码:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(); services.AddOptions();
services.Configure<SystemConfig>(Configuration.GetSection("SystemConfig"));
}
}
}

然后在Controller中进行注入并使用。

    public class ValuesController : Controller
{
private IOptions<SystemConfig> _setting; public ValuesController( IOptions<SystemConfig> setting)
{
_setting = setting;
} [HttpGet("setting")]
public IEnumerable<string> GetSetting()
{
var UploadFile = _setting.Value.UploadFile;
var AdminName = _setting.Value.Admin.Name;
var AdminAge = _setting.Value.Admin.Age;
var AdminAllow = _setting.Value.Admin.Allow; return new string[] { "value1", "value2" };
}
}

可以看到,这样在业务方法内通过 _setting 来都取配置信息就非常方便了。

三、自定义配置文件

以上操作的是系统默认的配置文件appsettings.json。如果我们需要增加自己的配置文件该如何处理?

新建一个配置文件:mysetting.json

{
"ConnString": "MySQL Connect String",
"SystemConfig": {
"UploadFile": "d:\\myfiles",
"AnnexUrl": "http://192.168.0.177:81/my",
"Admin": {
"Name": "myadmin",
"Age": "",
"Allow": "False"
},
"DefaultPassword": ""
}
}

在Startup类的ConfigureServices方法输入以下代码:

    public class Startup
{
public Startup(IConfiguration configuration,IHostingEnvironment env)
{
Configuration = configuration;
_env = env;
} public IConfiguration Configuration { get; }
public IHostingEnvironment _env { get; } public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(); var rootpath = _env.ContentRootPath;
var builder = new ConfigurationBuilder()
.SetBasePath(_env.ContentRootPath)
.AddJsonFile("mysetting.json",optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
var MyConfiguration = builder.Build(); services.AddOptions();
services.Configure<SystemConfig>(MyConfiguration.GetSection("SystemConfig"));
}
}

用自己创建的Configuration进行服务的注册,创建过程中需要用到IHostingEnvironment,这个对象在Startup类构建时进行注入。

剩下的用法和默认配置用法就一样了。

循序渐进学.Net Core Web Api开发系列【6】:配置文件appsettings.json的更多相关文章

  1. 循序渐进学.Net Core Web Api开发系列【0】:序言与目录

    一.序言 我大约在2003年时候开始接触到.NET,最初在.NET framework 1.1版本下写过代码,曾经做过WinForm和ASP.NET开发.大约在2010年的时候转型JAVA环境,这么多 ...

  2. 循序渐进学.Net Core Web Api开发系列【16】:应用安全续-加密与解密

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 应用安全除 ...

  3. 循序渐进学.Net Core Web Api开发系列【15】:应用安全

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍W ...

  4. 循序渐进学.Net Core Web Api开发系列【14】:异常处理

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍异 ...

  5. 循序渐进学.Net Core Web Api开发系列【13】:中间件(Middleware)

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  6. 循序渐进学.Net Core Web Api开发系列【12】:缓存

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  7. 循序渐进学.Net Core Web Api开发系列【11】:依赖注入

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  8. 循序渐进学.Net Core Web Api开发系列【10】:使用日志

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.本篇概述 本篇介 ...

  9. 循序渐进学.Net Core Web Api开发系列【9】:常用的数据库操作

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇描述一 ...

  10. 循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇讨论如 ...

随机推荐

  1. No module named flask.ext.script 解决方法

    把 .ext. 换成 _ 就OK了 from flask.ext.script import Manager from flask_script import Manager

  2. pandas 实现通达信里的MFI

    pandas 实现通达信里的MFI 算法里的关键点: combine()和rolling().sum()方法 combine -- 综合运算, rolling().sum() -- 滚动求和 利用pd ...

  3. HTML的文档类型:<!DOCTYPE >

    <!DOCTYPE> 声明:它不是 HTML 标签而且对大小写不敏感,而是指示 web 浏览器关于页面使用哪个 HTML 版本进行编写的指令.而且 声明必须是 HTML 文档的第一行,位于 ...

  4. 20155227 2016-2017-2 《Java程序设计》第五周学习总结

    20155227 2016-2017-2 <Java程序设计>第五周学习总结 教材学习内容总结 语法与继承架构 使用try...catch JVM会尝试执行try区块中的程序代码,如果发生 ...

  5. header()跳转

    if ($toNews == 1) { header('Location:/ucenter/pageMailBox/2'); exit; } PHP跳转页面,用 header() 函数 定义和用法 h ...

  6. netty学习总结(一)

    netty是一个nio框架,将java的nio进行了一个封装,形成了一个高性能,高可用的网络编程框架,很多的框架都是基于netty的,所以学好netty是很有用的,而且netty本身的代码结构设计,以 ...

  7. MYSQL 的 MASTER到MASTER的主主循环同步

    MYSQL 的 MASTER到MASTER的主主循环同步   刚刚抽空做了一下MYSQL的主主同步.把步骤写下来,至于会出现的什么问题,以后随时更新.这里我同步的数据库是TEST1.环境描述.   主 ...

  8. centos下配置nginx支持php

    添加nginx 默认主页index.php vim .../etc/nginx/conf.d/default.conf location / { root   /usr/share/nginx/htm ...

  9. Python_oldboy_常用模块(九)

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & pickle shelve xml处理 yaml处理 configpar ...

  10. ajax发送多个跨域请求回调不混乱

    var count = 0; var codes = ""; function refreshCache(urls){ try { var url = urls.split(&qu ...