系列目录

循序渐进学.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. Java基础-Java中23种设计模式之常用的设计模式

    Java基础-Java中23种设计模式之常用的设计模式 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.   一.设计模式分类 设计模式是针对特定场景给出的专家级的解决方案.总的来说设 ...

  2. Hadoop生态圈-Azkaban实现hive脚本执行

    Hadoop生态圈-Azkaban实现hive脚本执行 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 本篇博客中在HDFS分布式系统取的数据,而这个数据的是有之前我通过MapRed ...

  3. Java基础-Java数据类型

    Java基础-Java数据类型 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.数据类型的作用 数据类型就是一组值,以及这一组值上的操作,数据类型可以决定数据的存储方式,取值范围 ...

  4. python 手写队列

    #encoding=utf8 class MQueue: def __init__(self): self.data = [] def get(self): if self.data.__len__( ...

  5. Gnucash数据库结构

  6. mac 无法验证副本

    转: 这个是拆机后断了电源,导致时间不对,也就是说现在电脑的时间比U盘制作的时间还早,所以有这样的错误提示. 在终端里面修改时间请参考下面的代码,按回车键确认:date 062614102014.30 ...

  7. 【转】CocoaLumberjack——带颜色的Log

    CHENYILONG Blog [转]CocoaLumberjack--带颜色的Log - 趣味苹果开发 - 博客园 转自:趣味苹果开发   CocoaLumberjack--带颜色的Log Coco ...

  8. c# 防止sql注入对拼接sql脚本的各个参数处理

    调用方法:GameServerId = this.NoHtml(GameServerId);//GameServerId为一个拼接sql的参数 /// <summary> /// 过滤标记 ...

  9. 图解Android View的scrollTo(),scrollBy(),getScrollX(), getScrollY()

    https://blog.csdn.net/bigconvience/article/details/26697645 Android系统手机屏幕的左上角为坐标系,同时y轴方向与笛卡尔坐标系的y轴方向 ...

  10. Update Bits

    Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits be ...