自定义app.config的<configSections>
<configuration> <configSections> <!-- 定义自定义配置节 --> <sectionGroup name="ServiceConfig"> <section name="Debug" type="System.Configuration.NameValueSectionHandler"/> <section name="Release" type="System.Configuration.NameValueSectionHandler"/> </sectionGroup> </configSections> <!-- 使用自定义配置节 --> <ServiceConfig> <Debug> <add key="AUTHORITY" value="aa"/> <add key="APPLICATIONID" value="bb"/> <add key="CLIENTSECRET" value="cc"/> <add key="RESOURCE" value="dd"/> <!--<add key="URI" value="ee"/>--> <add key="URI" value="ff"/> </Debug> <Release> <add key="AUTHORITY" value="aa"/> <add key="APPLICATIONID" value="bb"/> <add key="CLIENTSECRET" value="cc"/> <add key="RESOURCE" value="dd"/> <!--<add key="URI" value="ee"/>--> <add key="URI" value="ff"/> </Release> </ServiceConfig> </configuration>
public class ServiceConfigSection { public CustomConfigSection Debug { get; set; } public CustomConfigSection Release { get; set; } } public class CustomConfigSection { public string Authority { get; set; } public string ApplicationId { get; set; } public string ClientSecret { get; set; } public string Resource { get; set; } public string Uri { get; set; } } public class ConfigurationReader { public static ServiceConfigSection ReadServiceConfiguration() { ServiceConfigSection serviceConfig = new ServiceConfigSection { Debug = ParseServiceSection("ServiceConfig/Debug"), Release = ParseServiceSection("ServiceConfig/Release") }; return serviceConfig; } private static CustomConfigSection ParseServiceSection(string sectionName) { var serviceSection = ConfigurationManager.GetSection(sectionName) as System.Collections.Specialized.NameValueCollection; if (serviceSection != null) { var config = new CustomConfigSection { Authority = serviceSection["AUTHORITY"], ApplicationId = serviceSection["APPLICATIONID"], ClientSecret = serviceSection["CLIENTSECRET"], Resource = serviceSection["RESOURCE"], Uri = serviceSection["URI"] }; return config; } return null; } }
使用:
/// <summary>
/// 获取令牌
/// </summary>
/// <returns></returns>
private static string GetToken()
{
string accessToken;
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
#if DEBUG
var serviceConfig = ServiceConfig.Debug;
#else
var ServiceConfig = _serviceConfig.Release;
#endif
ClientCredential clientCred = new ClientCredential(serviceConfig.ApplicationId, serviceConfig.ClientSecret);
Task<AuthenticationResult> vauthResult = new AuthenticationContext(serviceConfig.Authority).AcquireTokenAsync(serviceConfig.Resource, clientCred);
Task.WaitAll(vauthResult);
accessToken = vauthResult.Result.AccessToken;
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
WriteExceptions($"Exception : Failed to get Access Token! { ex.InnerException.Message}");
throw;
}
WriteExceptions($"Exception : Failed to get Access Token! {ex.Message}");
throw;
}
return accessToken;
}
参考:
https://www.cnblogs.com/yibinboy/articles/1649177.html
浙公网安备 33010602011771号