设为首页 加入收藏

TOP

.netcore2.1在控制器中和类中,获取appsettings中值的方法
2019-09-17 18:33:32 】 浏览:19
Tags:.netcore2.1 控制器 中和 获取 appsettings 方法

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

  在.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>();

 }

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

  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇我的微服务观,surging 2.0将会带.. 下一篇多功能串口调试助手XUTOPIA

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目