[step0] .net core 2.0 读取appsettings.json

.net core 2.0 使用了依赖注入的方式读取,首先在自己的项目中引入对应NuGet包 Microsoft.Extensions.Options.ConfigurationExtensions;

引入完成后,首先来看appsetting.json;

这里面的TestMsg要与你创建的对应类的类名一致,在调用方法后可以直接映射,注意这里的映射关系。

这时候要在Startup.cs中添加

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddOptions();

            services.Configure<Model.TestMsg>(Configuration.GetSection("TestMsg"));
        }

 

然后写一个BaseControler,如下:

public class BaseController : Controller
    {
        protected readonly IOptions<TestMsg> appconfig;

        public BaseController(IOptions<TestMsg> config )
        {
            appconfig = config;
        }
    }

 

接下来,让自己的控制器继承这个BaseController

 public class TestController : BaseController
    {
       
        public TestController(IOptions<TestMsg> config) :base(config)
        {
            
        }
       
       
        // GET: api/Test/5
        [HttpGet("{id}", Name = "Get")]
        public JsonResult Get(int id)
        {
            var temp = appconfig;
            return Json(temp);
        }
        
        // POST: api/Test
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }
        
        
    }

 

类(这里注意是属性而不是字段):

 public class TestMsg
    {
        public string Msg { get; set; }
    }

 

 

跑起来,调用

 

posted on 2018-03-28 15:15  SZMD.ls.nct  阅读(237)  评论(0)    收藏  举报

导航