一、前言
這是我學習的筆記,如果您看到有不對的地方,歡迎評論區指正!很多時候,我們將系統的配置都放入配置文件中,主要的目的就是為了方便修改!這就是我學習的目的。
二、具體學習
在學習獲取 AppSettings.json 的數據,首先我們需要了解 Configuration、ConfigurationBuilder 和 ConfigurationProvider .其中 ConfigurationProvider 對象承載着在編程中使用的配置信息,由ConfigurationBuilder 來完成,它利用 ConfigurationProvider 提取源數據將其轉化為 Configuration 對象。
我的配置文件 appsettings.json 文件如下
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "ConnectionStrings": { "DefaultConnection": "asdfasdfasdfasdfasdfas" }, "cnblogs": "My CNBlogs Address:https://www.cnblogs.com/gzbit-zxx/", "AppSettings": { "HttpUrl": "http://www.gzbit.com", "Copyright": "gzbit" }, "AllowedHosts": "*", "Person": [ { "name": "xfmtl", "company": "gzbit", "address": [ { "province": "Guizhou Province", "city": "Guiyang City" }, { "province": "Yunnan Province", "city": "Wuhua District" } ] }, { "name": "C# Study", "adress": "Microsoft" } ], "Book": { "name": "C# Program", "publish": "2020-08" } }
第一種直接使用方式
直接在 Controller 通過 ConfigurationBuilder 方式獲取.
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace WebApplication1.Controllers
{
public class ConfigController : Controller
{
public IActionResult Index()
{
//加載配置文件
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
//添加配置文件路徑
configurationBuilder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = configurationBuilder.Build();
//獲取博客園地址
var cnblogs = configuration["cnblogs"];
//獲取Book名稱
var bookname = configuration.GetValue<string>("Book:name");
//獲取幸福摩天輪的第一地區名稱
var addressName = configuration.GetValue<string>("Person:0:address:1:city");
//獲取C# 學習的名稱
var cname = configuration.GetValue<string>("Person:1:name");
//獲取所在公司
var companyName= configuration["AppSettings:Copyright"];
return Content(cnblogs);
}
}
}
測試案例截圖

第二種方式在 Startup.cs 中 Startup方法中配置
(1)、添加一個 Book.cs 類
namespace WebApplication1.Common
{
/// <summary>
/// 書
/// </summary>
public class Book
{
/// <summary>
/// 名稱
/// </summary>
public string Name { get; set; }
/// <summary>
/// 發布時間
/// </summary>
public string Publish { get; set; }
}
}
(2)、在 Startup.cs 中添加代碼
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication1.Common;
namespace WebApplication1
{
public class Startup
{
//定義 _configuration
public IConfiguration _configuration;
public Startup()
{
//加載配置文件
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
//添加配置文件路徑
configurationBuilder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
//加載文件
_configuration = configurationBuilder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//獲取配置文件中 Book 數據
services.Configure<Book>(_configuration.GetSection("Book"));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
(3)、在 Controller 中調用
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using WebApplication1.Common;
namespace WebApplication1.Controllers
{
public class ConfigController : Controller
{
//定義
private readonly Book _book;
/// <summary>
/// 構造函數中注入Book
/// </summary>
/// <param name="options"></param>
public ConfigController(IOptions<Book> options) {
_book = options.Value;
}
public IActionResult Index()
{
//獲取書本名稱
var name = _book.Name;
//獲取書本的發布時間
var publish = _book.Publish;
return Content(_book.Name);
}
}
}
(4)、案例截圖

第三種使用方式,也是 .net core web 默認的方式。
(1)、在 Startup.cs 中代碼如下,同樣我們也需要創建相應的類。如 Book.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.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication1.Common;
namespace WebApplication1
{
public class Startup
{
// 定義 Configuration
public IConfiguration Configuration { get; }
/// <summary>
/// 依賴注入 IConfiguration
/// </summary>
/// <param name="configuration"></param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//獲取配置文件中 Book 數據
services.Configure<Book>(Configuration.GetSection("Book"));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
(2)、在 Controller 使用
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using WebApplication1.Common;
namespace WebApplication1.Controllers
{
public class ConfigController : Controller
{
//定義
private readonly Book _book;
/// <summary>
/// 構造函數中注入Book
/// </summary>
/// <param name="options"></param>
public ConfigController(IOptions<Book> options) {
_book = options.Value;
}
public IActionResult Index()
{
//獲取書本名稱
var name = _book.Name;
//獲取書本的發布時間
var publish = _book.Publish;
return Content(_book.Name);
}
}
}
這就是讀取 appsettings 的方式,重點還是讀取字符串的三種方式:字符串讀取:configuration["cnblogs"]、configuration.GetValue<string>("Book:name"),對象讀取:Configuration.GetSection("Book") 。
