在 .NET Core 项目中,配置文件有着举足轻重的地位;与.NetFramework 不一样的是,.NET Core 的配置文件都以 .json 结尾,这表示一个标准的 json 格式的文件;一个标准的 Asp.Net Core MVC 项目,必定带着一个 appsettings.json 文件,该文件即是项目默认配置文件,这和基于 .NetFramework 建立的 Asp.Net Web Application (默认配置名称:App.config) 有着根本的不一样,今天咱们就学习如何添加自定义配置到文件中,并把该配置在程序中读取出来;而后再经过使用 host.json 这个配置文件使程序运行于多个端口。css
1.1 appsettings.json 文件是一个标准的 json 结构的文件,这表示你只要按照 json 的结构写入该文件,不管什么内容,都能在程序中自动读取,当咱们建立好 MVC 项目后,系统就自动帮咱们建立好 appsettings.json 文件,其默认内容以下:java
{
"Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*" }
1.2 下面咱们加一个配置节点 "book":"博客园精华文章选集"json
{
"Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "book":"博客园精华文章选集" }
1.3 在控制器 Controllers/HomeController.cs 中将该节点内容设置为网页标题输出,记得引用命名空间app
using Microsoft.Extensions.Configuration;
在 Index 方法中加入参数 IConfiguration,以下学习
public IActionResult Index([FromServices]IConfiguration cfg) { return View(); }
1.4 输入命令 dotnet run 启动项目,结果以下,读取自定义配置成功ui
1.5 将配置文件节点转换为实体类url
{
"Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "book":"博客园精华文章选集", "customer":{ "name":"ron.liang", "gender":"man", "job":"coder" } }
public class Customer{ public string Name { get; set; } public string Gender{get;set;} public string Job{get;set;} }
{
"server.urls": "http://0.0.0.0:12006;http://0.0.0.0:12007" }
public static IWebHostBuilder CreateWebHostBuilder(string[] args) { var hostConfiguration = new ConfigurationBuilder().AddJsonFile("hosting.json").Build(); return WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseConfiguration(hostConfiguration); }