using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace CoreApi.Common { public class ConfigFunction { public static IConfiguration Configuration { get; set; } public static string GetConfig(string configName) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); return Configuration[configName]; //var a = Configuration[configName]; //var aa = Configuration["SiteConfig:Info"]; } } }
appsettings.json 文件:
{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-CoreWeb-E8C77D58-03FF-413B-B3DF-48B1167BC0F6;Trusted_Connection=True;MultipleActiveResultSets=true" }, "Logging": { "LogLevel": { "Default": "Warning" } }, "SiteConfig": { "Name": "LineZero's Blog", "Info": "ASP.NET Core 开发及跨平台,配置文件读取" }, "AllowedHosts": "*" }
控制器中读取配置文件:
先创建配置文件的节点对象,然后注入
namespace CoreWeb.Models { public class SiteConfig { public string Name { get; set; } public string Info { get; set; } } }
SiteConfig Config; public HomeController(IOptions<SiteConfig> option) { Config = option.Value; } public IActionResult Index() { var a = Config.Info; var b = Config.Name; Common.CommonFunction.GetConfig(); return View(); }
注意:
控制器中读取配置文件,要先在Startup.cs中的ConfigureServices方法中注入 services.Configure<SiteConfig>(Configuration.GetSection("SiteConfig"));