dotnetCore利用Configuration读取自定义配置文件
在appsettings.json中:
- {
- "Logging":{
- "LogLevel":{
- "Default":"Warning"
- }
- },
- "Name":"Cas.Api",
- "AllowedHosts":"*",
- "urls":"http://0.0.0.0:8080",
- "ConsulUrl":"http://127.0.0.1:8500",
- "ConnectionStrings":{
- "DefaultConnection":"server=192.168.2.100;port=3306;database=dati;user=root;password=888888.;CharSet=utf8;"
- },
- "appid":"wx*******",
- "secret":"xxx*********"
- }
在controller中:
- private readonly IConfiguration _configuration;
- publicAppController(IConfiguration configuration)
- {
- _configuration = configuration;
- }
- /// <summary>
- /// 获得微信OPENID
- /// </summary>
- /// <param name="code"></param>
- /// <returns></returns>
- [HttpGet]
- public string GetOpenId(string code)
- {
- string url ="https://api.weixin.qq.com/sns/jscode2session";
- string appid = _configuration.GetValue<string>("appid");// "";
- string secret = _configuration.GetValue<string>("secret");// "";
- string js_code = code;
- string grant_type ="authorization_code";
- try
- {
- using(var handler =newHttpClientHandler
- {
- ServerCertificateCustomValidationCallback=(sender, certificate, chain, sslPolicyErrors)=>true
- })
- using(var http =newHttpClient(handler))
- {
- var response = http.GetStringAsync(url +"?appid="+ appid +">secret="+ secret +">js_code="+ js_code +">grant_type="+ grant_type);
- GetOpenIdResult openIdResult =JsonConvert.DeserializeObject<GetOpenIdResult>(response.Result);
- if(openIdResult == null||openIdResult.openid == null)
- {
- return"";
- }
- return openIdResult.openid;
- }
- }
- catch(System.Exception ex)
- {
- return"";
- }
- }