媒介
最近在研讨把asp.net顺序移植到linux上,恰好.net core出来了,就进行了进修。
移植代码基础顺遂,然则发明.net core中没有ConfigurationManager,没法读写设置文件,零丁写个xml之类的嫌贫苦,就谷歌了下,发明了个要领,遂纪录以下,轻易今后查找:
要领以下
设置文件构造
public class DemoSettings { public string MainDomain { get; set; } public string SiteName { get; set; } }
appsettings.json中显现结果
appsettings.json
{ "DemoSettings": { "MainDomain": "http://www.mysite.com", "SiteName": "My Main Site" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } }
设置Services
原设置
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); }
自定义
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); // Added - uses IOptions<T> for your settings. services.AddOptions(); // Added - Confirms that we have a home for our DemoSettings services.Configure<DemoSettings>(Configuration.GetSection("DemoSettings")); }
然后把设置注入进响应的Controller后就能够运用了
public class HomeController : Controller { private DemoSettings ConfigSettings { get; set; } public HomeController(IOptions<DemoSettings> settings) { ConfigSettings = settings.Value; } public IActionResult Index() { ViewData["SiteName"] = ConfigSettings.SiteName; return View(); } }
总结
以上就是core Web中运用appsettings.json设置文件的实例详解(ASP.NET )的细致内容,更多请关注ki4网别的相干文章!