csharp 从appsettings.json获取价值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 从appsettings.json获取价值相关的知识,希望对你有一定的参考价值。

private readonly IConfiguration _configuration;

public Tools(IConfiguration configuration)
{
    _configuration = configuration;
}

public string GetConfigKey(string categoryName, string keyName)
{
    string keyValue = null;
    try
    {
        keyValue = _configuration.GetSection(categoryName)[keyName].ToString();
    }
    catch (Exception ex)
    {
        string error = string.Format("Error in getting this '{0}' key from config file", keyName);
        //SendEmail("noreply@dickerdata.com.au", "it.developers@dickerdata.com.au", "Error in config key", error);
        SendEmail(GetConfigKey("AppConfig", "EmailSendFrom"), GetConfigKey("AppConfig", "EmailSendTo"), string.Format("Error in config key. Error details: {0}", error), GetConfigKey("AppConfig", "EmailCCList"));

        string log = "Config key not found";

        RegisterEventLog(error, log, EventLogEntryType.Error);
    }

    return keyValue;
}

// Event log entry
public void RegisterEventLog(string strEvent, string log, EventLogEntryType logType, string source = "Email Service Application")
{
    // Application source in system event log

    try
    {
        if (!EventLog.SourceExists(source))
        {
            EventLog.CreateEventSource(source, log);
        }

        EventLog.WriteEntry(source, strEvent, logType);
    }
    catch (Exception ex)
    {
        //DDAppLogger.Add("EmailService", "RegisterEventLog", "RegisterEventLog", ex.ToString(), -1, "UNKNOWN", "SYSTEM", true);
        //throw ex;
    }
}

以上是关于csharp 从appsettings.json获取价值的主要内容,如果未能解决你的问题,请参考以下文章

从不同项目访问 appsettings.json

从 appsettings.json 读取动态参数

无法从类库访问 appsettings.json

从appsettings.json读取entity.Framework的ConnectionString

从 .NET Core 2 中的类中读取 appsettings.json

无法从 asp dot net 3.1 中的 appsettings.json 读取字符串数组