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

本文介绍了在.NET Core项目中如何从配置文件(appsettings.json)读取参数信息,包括数据库连接信息、自定义参数配置等。通过在控制器和自定义类中注入IConfiguration接口,可以轻松访问配置项。同时,详细展示了TencentSignHelper类的实现,用于获取Tencent API的配置,并在Startup类中注册该服务。

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

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

 }

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

  

转载于:https://www.cnblogs.com/personblog/p/10790867.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值