ASP.NET Core快速入门学习笔记(第2章:配置管理)
课程链接:http://video.jessetalk.cn/course/explore
良心课程,大家一起来学习哈!
任务9:配置介绍
- 命令行配置
- Json文件配置
- 从配置文件文本到c#对象实例的映射 - Options 与 Bind
- 配置文件热更新
- 框架设计:Configuration
任务10:命令行配置
新建一个项目CommandLineSample--控制台应用(.NET Core)
依赖性右键--管理NuGet程序包--下载microsoft.aspnetcore.all
传入参数
using System;
using Microsoft.Extensions.Configuration;
namespace CommandLineSample
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddCommandLine(args);
var configuration = builder.Build();
Console.WriteLine($"name: {configuration ["name"]}");
Console.WriteLine($"age: {configuration["age"]}");
Console.ReadLine();
}
}
}
需要通过项目右键--调试--输入参数:name=mingsonzheng age=18
启动项目,得到结果:
默认参数
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
namespace CommandLineSample
{
class Program
{
static void Main(string[] args)
{
var settings = new Dictionary<string, string>
{
{"name", "mingsonzheng" },
{"age", "18" }
};
var builder = new ConfigurationBuilder()
.AddInMemoryCollection(settings)
.AddCommandLine(args);
var configuration = builder.Build();
Console.WriteLine($"name: {configuration ["name"]}");
Console.WriteLine($"age: {configuration["age"]}");
Console.ReadLine();
}
}
}
清空应用程序参数
启动项目
通过PowerShell运行程序,默认参数与传入参数
PS C:\WINDOWS\system32> d:
PS D:\> cd D:\jessetalk\CommandLineSample\CommandLineSample\bin\Debug\netcoreapp2.1
PS D:\jessetalk\CommandLineSample\CommandLineSample\bin\Debug\netcoreapp2.1> dir
目录: D:\jessetalk\CommandLineSample\CommandLineSample\bin\Debug\netcoreapp2.1
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2019-01-23 23:54 244607 CommandLineSample.deps.json
-a---- 2019-01-24 0:01 5632 CommandLineSample.dll
-a---- 2019-01-24 0:01 604 CommandLineSample.pdb
-a---- 2019-01-23 23:54 240 CommandLineSample.runtimeconfig.dev.json
-a---- 2019-01-23 23:54 154 CommandLineSample.runtimeconfig.json
PS D:\jessetalk\CommandLineSample\CommandLineSample\bin\Debug\netcoreapp2.1> dotnet CommandLineSample.dll
name: mingsonzheng
age: 18
PS D:\jessetalk\CommandLineSample\CommandLineSample\bin\Debug\netcoreapp2.1> dotnet CommandLineSample.dll name=jim age=22
name: jim
age: 22
任务11:Json文件配置
新建一个项目JsonComfigSample--控制台应用(.NET Core)
依赖性右键--管理NuGet程序包--下载microsoft.aspnetcore.all
添加Json文件:项目右键--添加新建项class.json
{
"ClassNo": "1",
"ClassDesc": "ASP.NET Core 101",
"Students": [
{
"name": "mingsonzheng",
"age": "18"
},
{
"name": "jim",
"age": "28"
},
{
"name": "tom",
"age": "38"
}
]
}
由于class.json不在bin\Debug目录下,所以默认不会被编译,需要修改它的属性,文件右键属性
using System;
using Microsoft.Extensions.Configuration;
namespace JsonComfigSample
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("class.json");
Console.ReadLine();
}
}
}
启动项目,可以看到class.json被复制到bin\Debug目录,这样dll就可以读取到class.json文件
读取json文件
using System;
using Microsoft.Extensions.Configuration;
namespace JsonComfigSample
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("class.json");
// 调用Build之前请确保拷贝的class.json文件没有格式错误
var configuration = builder.Build();
Console.WriteLine($"ClassNo: { configuration["ClassNo"]}");
Console.WriteLine($"ClassDesc: { configuration["ClassDesc"]}");
Console.WriteLine("Students");
Console.Write(configuration["Students:0:name"]);
Console.WriteLine(configuration["Students:0:age"]);
Console.Write(configuration["Students:1:name"]);
Console.WriteLine(configuration["Students:1:age"]);
Console.Write(configuration["Students:2:name"]);
Console.WriteLine(configuration["Students:2:age"]);
Console.ReadLine();
}
}
}
启动项目
任务12:Bind读取配置到C#实例
新建一个ASP.NET Core Web 应用程序OptionsBindSample,直接选择 空,确定
在Startup.cs中通过依赖注入添加configuration
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
项目右键,新建项,添加一个类Class.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OptionsBindSample
{
public class Class
{
public int ClassNo { get; set; }
public string ClassDesc { get; set; }
public List<Student> Students { get; set; }
}
public class Student
{
public string Name { get; set; }
public string Age { get; set; }
}
}
项目右键,新建项,添加一个Json文件appsettings.json
为什么取名appsettings.json呢?
因为Program.cs中的CreateDefaultBuilder默认读取一个名为appsettings.json的Json文件并把它的内容添加到配置文件
拷贝前面的内容到appsettings.json
{
"ClassNo": "1",
"ClassDesc": "ASP.NET Core 101",
"Students": [
{
"name": "mingsonzheng",
"age": "18"
},
{
"name": "jim",
"age": "28"
},
{
"name": "tom",
"age": "38"
}
]
}
在Startup.cs中通过Bind读取配置
app.Run(async (context) =>
{
var myClass = new Class();
Configuration.Bind(myClass);// Bind读取配置
await context.Response.WriteAsync($"ClassNo: { myClass.ClassNo}");
await context.Response.WriteAsync($"ClassDesc: { myClass.ClassDesc}");
await context.Response.WriteAsync($" {myClass.Students.Count } Students");
});
完整Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace OptionsBindSample
{
public class Startup
{
public IConfiguration Configuration { get; set; }
// 通过依赖注入添加configuration
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
var myClass = new Class();
Configuration.Bind(myClass);// Bind读取配置
await context.Response.WriteAsync($"ClassNo: { myClass.ClassNo}");
await context.Response.WriteAsync($"ClassDesc: { myClass.ClassDesc}");
await context.Response.WriteAsync($" {myClass.Students.Count } Students");
});
}
}
}
启动项目
任务13:在Core Mvc中使用Options
在项目OptionsBindSample新建三个文件夹目录如下
在Controllers文件夹右键,添加一个控制器,默认,HomeController
在Home文件夹右键,添加一个视图,默认,Index
在Startup.cs中注释掉这一段代码,不然会把整个管道提交,只输出这一段
//app.Run(async (context) =>
//{
// var myClass = new Class();
// Configuration.Bind(myClass);// Bind读取配置
// await context.Response.WriteAsync($"ClassNo: { myClass.ClassNo}");
// await context.Response.WriteAsync($"ClassDesc: { myClass.ClassDesc}");
// await context.Response.WriteAsync($" {myClass.Students.Count } Students");
//});
依赖注入配置添加MVC
services.AddMvc();
使用默认路由
app.UseMvcWithDefaultRoute();
HomeController中通过IOptions方式依赖注入
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace OptionsBindSample.Controllers
{
public class HomeController : Controller
{
private readonly Class _myClass;
// 通过IOptions方式依赖注入
public HomeController(IOptions<Class> classAccesser)
{
_myClass = classAccesser.Value;
}
public IActionResult Index()
{
return View(_myClass);
}
}
}
在Index中定义模型,输出
@model OptionsBindSample.Class
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<h4>Class No: @Model.ClassNo</h4>
<h4>Class Desc: @Model.ClassDesc</h4>
<h3>
Students:
</h3>
<div>
@foreach (var student in Model.Students)
{
<span>Name: @student.Name</span>
<span>Age: @student.Age</span>
}
</div>
注册Class,可以通过Configuration读取到option
services.Configure<Class>(Configuration);
Startup.cs完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace OptionsBindSample
{
public class Startup
{
public IConfiguration Configuration { get; set; }
// 通过依赖注入添加configuration
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// 注册Class,可以通过Configuration读取到option
services.Configure<Class>(Configuration);
// 依赖注入配置添加MVC
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// 使用默认路由
app.UseMvcWithDefaultRoute();
//app.Run(async (context) =>
//{
// var myClass = new Class();
// Configuration.Bind(myClass);// Bind读取配置
// await context.Response.WriteAsync($"ClassNo: { myClass.ClassNo}");
// await context.Response.WriteAsync($"ClassDesc: { myClass.ClassDesc}");
// await context.Response.WriteAsync($" {myClass.Students.Count } Students");
//});
}
}
}
启动项目
如果仅仅在视图中使用options的话,HomeController的代码有点多余,可以直接在视图中注入
Index
@using Microsoft.Extensions.Options;
@inject IOptions<OptionsBindSample.Class> ClassAccesser
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<h4>Class No: @ClassAccesser.Value.ClassNo</h4>
<h4>Class Desc: @ClassAccesser.Value.ClassDesc</h4>
<h3>
Students:
</h3>
<div>
@foreach (var student in ClassAccesser.Value.Students)
{
<span>Name: @student.Name</span>
<span>Age: @student.Age</span>
}
</div>
HomeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace OptionsBindSample.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
启动项目可以得到同样结果
任务14:配置的热更新
ASP.NET修改web.config后站点会自动重启实现热更新
ASP.NET Core不同,实现如下:
将Index的这一行
@inject IOptions<OptionsBindSample.Class> ClassAccesser
修改为
@inject IOptionsSnapshot<OptionsBindSample.Class> ClassAccesser
启动项目
修改appsettings的ClassNo为222,保存
"ClassNo": "222",
刷新网页
实现原理
对比控制台程序JsonComfigSample的Program读取配置文件
// 第二个参数表示文件不存在时是否抛异常
// 第三个参数表示配置文件更新的时候是否重新加载
var builder = new ConfigurationBuilder()
.AddJsonFile("class.json",false,true);
而在ASP.NET Core程序OptionsBindSample在Program中的CreateDefaultBuilder的源码实现了
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
WebHost源码:
https://github.com/aspnet/MetaPackages/blob/master/src/Microsoft.AspNetCore/WebHost.cs
源码里面实现热更新(165行)
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
由于它是WebHostBuilder的一个扩展函数,所以可以覆盖该方法
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
// 如果业务场景不需要一个线程一直关注配置文件变更,可以关闭热更新
.ConfigureAppConfiguration(config => { config.AddJsonFile("appsettings.json", false, false); })
.UseStartup<Startup>();
启动项目,修改配置文件,保存,刷新网页,内容不会热更新
任务15:配置框架设计浅析
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。
欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。
如有任何疑问,请与我联系 (MingsonZheng@outlook.com) 。
ASP.NET Core快速入门学习笔记(第2章:配置管理)的更多相关文章
- ASP.NET Core快速入门--学习笔记系列文章索引目录
课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 抓住国庆假期的尾巴完成了此系列课程的学习笔记输出! ASP.NET Core快 ...
- ASP.NET Core快速入门学习笔记(第3章:依赖注入)
课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务16:介绍 1.依赖注入概念详解 从UML和软件建模来理解 从单元测试来理 ...
- ASP.NET Core快速入门学习笔记(第1章:介绍与引入)
课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务1:课程介绍 任务2:环境安装 下载地址:https://dotnet.m ...
- 【笔记目录2】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总
当前标签: ASP.NET Core快速入门 共2页: 上一页 1 2 任务27:Middleware管道介绍 GASA 2019-02-12 20:07 阅读:15 评论:0 任务26:dotne ...
- 【笔记目录1】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总
当前标签: ASP.NET Core快速入门 共2页: 1 2 下一页 任务50:Identity MVC:DbContextSeed初始化 GASA 2019-03-02 14:09 阅读:16 ...
- ASP.NET Core Web开发学习笔记-1介绍篇
ASP.NET Core Web开发学习笔记-1介绍篇 给大家说声报歉,从2012年个人情感破裂的那一天,本人的51CTO,CnBlogs,Csdn,QQ,Weboo就再也没有更新过.踏实的生活(曾辞 ...
- 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移
不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.superviso ...
- 【原创】SpringBoot & SpringCloud 快速入门学习笔记(完整示例)
[原创]SpringBoot & SpringCloud 快速入门学习笔记(完整示例) 1月前在系统的学习SpringBoot和SpringCloud,同时整理了快速入门示例,方便能针对每个知 ...
- ASP.NET Core MVC 网站学习笔记
ASP.NET Core MVC 网站学习笔记 魏刘宏 2020 年 2 月 17 日 最近因为” 新冠” 疫情在家办公,学习了 ASP.NET Core MVC 网站的一些知识,记录如下. 一.新建 ...
随机推荐
- LOJ#2087 国王饮水记
解:这个题一脸不可做... 比1小的怎么办啊,好像没用,扔了吧. 先看部分分,n = 2简单,我会分类讨论!n = 4简单,我会搜索!n = 10,我会剪枝! k = 1怎么办,好像选的那些越大越好啊 ...
- pwn-格式化字符串漏洞
原理:因为没有正确使用printf()函数 正确使用 : printf('%s',str) 不正规使用:printf(str) 控制字符串str可以爆出stack内内容从而实现任意地址读或者任意地址写 ...
- FFT & FNT 简要整理
几周前搞了搞--有点时间简要整理一下,诸多不足之处还请指出. 有哪些需要理解的地方? 点值表示:对于多项式 \(A(x)\),把 \(n\) 个不同的 \(x\) 代入,会得出 \(n\) 个不同的 ...
- 你值得拥有的Mac PS滤镜插件和特效处理软件合集,不要错过!
以下几款是Mac上强大的Photoshop滤镜插件和特效,可以让我们更加高效率的使用PS,设计和处理出精美的图片. 1. Alien Skin Eye Candy Eye Candy是一款强大酷炫的P ...
- 神经网络1_neuron network原理_python sklearn建模乳腺癌细胞分类器(推荐AAA)
sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...
- Linux之 proc文件系统
用户态与内核态交互的接口之一,管理方式与普通文件相同每个节点的文件权限(读/写)决定其查看和配置权限大量LINUX系统参数和状态信息可通过proc节点查看或配置/proc/<pid>/:查 ...
- python之路(4)高阶函数和python内置函数
前言 函数式编程不用变量保存状态,不改变变量 内置函数 高阶函数 把函数当作参数传给另一个对象 返回值中包含函数 使用的场景演示: num_test = [1,2,10,5,8,7] 客户说 :对上述 ...
- JS中JSON和string字符串相互转换
在Firefox,chrome,opera,safari,ie9,ie8等高级浏览器直接可以用JSON对象的stringify()和parse()方法. JSON.stringify(obj)将JSO ...
- MATLAB cftool工具数据拟合结果好坏判断
SSE和RMSE比较小 拟合度R接近于1较好 * 统计参数模型的拟合优度 1.误差平方和(SSE) 2. R-Square(复相关系数或复测定系数) 3. Adjusted R-Square(调整自由 ...
- Standford NLP study
Homepage https://stanfordnlp.github.io/CoreNLP/index.html Source Code: https://github.com/stanfordnl ...