一般我們在開發項目中,都會從配置文件中獲取資料庫連接信息、自定義參數配置信息等。 在.netcore中在控制器和自定義類中,獲取配置文件中參數方式如下: appsettings.json controller中調用如下紅色字體,註入TencentSignHelper類後,我們就可以像調用靜態方法一樣 ...
一般我們在開發項目中,都會從配置文件中獲取資料庫連接信息、自定義參數配置信息等。
在.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>();
}
今天就寫到這,希望對需要的博有有所幫助。