Onyx系统Onyx系统10-14 02:57

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

 }

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

  

程序之家二维码

小额赞赏

000
评论