asp.net Core利用Configuration读取自定义配置文件
自定义配置文件:
在根目录建一个Config文件夹和config.json配置文件
{ "Person": { "Name": "zhangsan2222", "Age": 18 } }
Program.cs文件:
namespace WebApplication1 { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((c, h) => { h.AddJsonFile($"Config/config.json",true,true); }) .UseStartup<Startup>(); } }
Controller文件:
[Route("[Controller]")] public class OptionsController : Controller { private readonly IConfiguration _configuration; public OptionsController(IConfiguration configuration) { _configuration = configuration; } [HttpGet("Index")] public IActionResult Index() { var Name= _configuration.GetValue<String>("Person:Name"); return View(nameof(Index),Name); }
view文件:
@model String @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <h1>@Model.ToString()</h1> </body> </html>
绑定到实体类:
////第一种绑定 //PersonOptions option = new PersonOptions(); ////配置文件绑定Person绑定到该PersonOptions对象上 //Configuration.Bind("Person", option); ////注入 //services.AddSingleton(option); ////第二种绑定 PersonOptions option = new PersonOptions(); Configuration.GetSection("Person").Bind(option); services.AddSingleton(option);
实体类:
public class PersonOptions { public String Name { get; set; } public int Age { get; set; } }
controller:
[Route("[Controller]")] public class OptionsController : Controller { private readonly PersonOptions _options; public OptionsController(PersonOptions options) { _options = options; } [HttpGet("Index")] public IActionResult Index() { return View(nameof(Index), _options.Name); } }