当前位置: 移动技术网 > IT编程>开发语言>.net > .netcore2.1在控制器中和类中,获取appsettings中值的方法

.netcore2.1在控制器中和类中,获取appsettings中值的方法

2019年04月30日  | 移动技术网IT编程  | 我要评论

异世药皇txt下载,nitrome必死,脏话骂人宝典

  一般我们在开发项目中,都会从配置文件中获取数据库连接信息、自定义参数配置信息等。

  在.netcore中在控制器和自定义类中,获取配置文件中参数方式如下:

  • appsettings.json
{
  
  "api": {
    "tencentapi": "https://api.weixin.qq.com/cgi-bin"
  },
  "tencentjsjdk": {
    "appid": "asdfasdf",
    "secret": "asfxvzvzx"
  }
}
  • controller中调用如下红色字体,注入tencentsignhelper类后,我们就可以像调用静态方法一样,调用_jssignhelper里面的方法了。
 private applicationdbcontext _identitydb;
        private readonly iconfiguration _configuration;
        private tencentsignhelper _jssignhelper;
        private string appid;
        public sharecontroller(applicationdbcontext identitydb, iconfiguration configuration, tencentsignhelper jssignhelper)
        {
            _identitydb = identitydb;
            _configuration = configuration;
            appid = _configuration.getsection("tencentjsjdk:appid").value;
            _jssignhelper = jssignhelper;

        }
  • 类中调用
public class tencentsignhelper
    {
        private  string _tencentapi { get; set; }
        private  string _appid { get; set; }
        private  string _appsecret { get; set; }

        public tencentsignhelper(iconfiguration config)
        {
           
            _tencentapi = config["api:tencentjsjdkbaseapi"]; 
            _appid = config["tencentjsjdk:appid"];
            _appsecret = config["tencentjsjdk:secret"];
        }
}

  需要注意的是tencentsignhelper需要在startup类中configureservices方法中进行注入服务

  public void configureservices(iservicecollection services)
 {
            services.addmvc().setcompatibilityversion(compatibilityversion.version_2_1);

            services.addsingleton<tencentsignhelper>();

 }

  今天就写到这,希望对需要的博有有所帮助。

  

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网