ASP.NET Core快速入门(Jessetalk)(第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/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。

如有任何疑问,请与我联系 ([email protected]) 。

原文地址:https://www.cnblogs.com/MingsonZheng/p/10312209.html

时间: 2024-08-02 05:42:07

ASP.NET Core快速入门(Jessetalk)(第2章:配置管理)的相关文章

【ASP.NET Core快速入门】(二)部署到IIS

原文:[ASP.NET Core快速入门](二)部署到IIS 配置IIS模块 ASP.NET Core Module载地址:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-module?tabs=aspnetcore2x 安装后再IIS管理器模块页面会出现aspnetcoremodule 新建网站 修改应用池 网站发布 控制台方式 dotnet publish发布到项目文件的bin/deb

ASP.NET Core快速入门(Jessetalk)(第三章:依赖注入)

课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务16:介绍 1.依赖注入概念详解 从UML和软件建模来理解 从单元测试来理解 2.ASP.NET Core 源码解析 任务17:从UML角度来理解依赖 1.什么是依赖 当一个类A完成某个任务需要另一个类B来帮助时,A就对B产生了依赖 例如CustomerController需要对customer进行新增或查找时用到EF,则对EF的Context产生了依赖 var cont

【ASP.NET Core快速入门】(一)环境安装

下载.NET Core SDK 下载地址:https://www.microsoft.com/net/download/windows https://www.microsoft.com/net/learn/get-started/windows 安装vs2017,安装的时候选择安装core跨平台 在控制台创建ASP.NET Core应用程序 在程序安装后,可以在控制台输入dotnet进行创建core应用程序 输入dotnet  --help查看命令帮助 .NET 命令行工具 (2.1.2) 使

【ASP.NET Core快速入门】(三)准备CentOS和Nginx环境

基本软件 VMware虚拟机 centos:http://isoredirect.centos.org/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-1708.iso centos安装 打开VMware虚拟机,选择文件----新建虚拟机 一般下载好的CentOS系统放在VMware文件夹下 选择网络方式(一般NAT就够了) 后面的都选择默认的就行了 然后运行就可以了 语言选英文 选择位置 然后开始安装 输入密码root123 然后等待安装完成就可以了,

【ASP.NET Core快速入门】(十二)JWT 设计解析及定制

前言 上一节我们讲述的书如何使用jwt token,而且上一节的token是要加Authorization:bearer XXXXXXXXXXXX才能访问. 这一节我们来研究如何自定义类似jwt的token验证,也就是说直接从header中拿取我们想要的token 自己定制JWT 首先,继续在上一节的JwtAuthSample项目中的Startup.cs中的ConfigureServices方法中注释掉以下内容,然后自定义jwt token public void ConfigureServic

【ASP.NET Core快速入门】(十四)MVC开发:UI、 EF + Identity实现

前言 之前我们进行了MVC的web页面的Cookie-based认证实现,接下来的开发我们要基于之前的MvcCookieAuthSample项目做修改. MvcCookieAuthSample项目地址:http://www.cnblogs.com/wyt007/p/8128186.html UI 我们首先在AccountController中添加两个Action public IActionResult SignIn() { return View(); } public IActionResu

Asp.Net Core 快速入门-在Centos 上安装Nginx

第一步:添加CentOS 7EPEL 库 在终端运行一下命令 sudo yum install epel-release 第二步:安装Nginx 在终端运行命一下 sudo yum install nginx 你回答“yes”的提示后,nginx会完成安装到你的虚拟专用服务器(VPS) 第三步:启动Nginx sudo systemctl start nginx 启动完成之后我们就可以用CentOS的IP和80端口访问Nginx了 如果无法访问,说明还是有问题 If you are runnin

005.Getting started with ASP.NET Core MVC and Visual Studio -- 【VS开发asp.net core mvc 入门】

Getting started with ASP.NET Core MVC and Visual Studio VS开发asp.net core mvc 入门 2017-3-7 2 分钟阅读时长 本文内容 1.Install Visual Studio and .NET Core 安装 VS 与 .NET Core 2.Create a web app 创建一个 web 应用 By Rick Anderson This tutorial will teach you the basics of

【第三篇】ASP.NET MVC快速入门之安全策略(MVC5+EF6)

[第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策略(MVC5+EF6) [第四篇]ASP.NET MVC快速入门之完整示例(MVC5+EF6) [番外篇]ASP.NET MVC快速入门之免费jQuery控件库(MVC5+EF6) 请关注三石的博客:http://cnblogs.com/sanshi 表单身份验证(Forms Authentication