繁体   English   中英

AppSettings 后备/默认值?

[英]AppSettings fallback/default value?

ASP.NET

对于我使用的每个 appSetting,我想指定一个值,如果在 appSettings 中找不到指定的键,将返回该值。 我正要创建一个 class 来管理这个,但我认为这个功能可能已经在 .NET 框架的某个地方?

.NET 中是否有 NameValueCollection/Hash/etc-type class 可以让我指定一个键和一个后备/默认值 - 并返回键的值或指定的值?

如果有,我可以将 appSettings 放入该类型的 object 中,然后再调用它(从各个地方)。

我不相信.NET内置任何内容可以提供您正在寻找的功能。

您可以创建一个基于Dictionary<TKey, TValue> ,它提供TryGetValue的重载以及一个默认值的附加参数,例如:

public class MyAppSettings<TKey, TValue> : Dictionary<TKey, TValue>
{
    public void TryGetValue(TKey key, out TValue value, TValue defaultValue)
    {
        if (!this.TryGetValue(key, out value))
        {
            value = defaultValue;
        }
    }
}

您可能可以使用string s而不是保持通用。

如果这些是选项,那么还有来自Silverlight和WPF世界的DependencyObject

当然,最简单的方法是使用NameValueCollection

string value = string.IsNullOrEmpty(appSettings[key]) 
    ? defaultValue 
    : appSettings[key];

key在字符串索引器上可以为null 但我明白在多个地方做这件事很痛苦。

这就是我的工作。

WebConfigurationManager.AppSettings["MyValue"] ?? "SomeDefault")

对于布尔值和其他非字符串类型......

bool.Parse(WebConfigurationManager.AppSettings["MyBoolean"] ?? "false")

您可以创建自定义配置部分,并使用DefaultValue属性提供默认值。 有关该说明,请点击此处

ASP.NET 的 ConfigurationManager 提供了该功能。 您可以使用.Get<MySectionType>().Bind(mySectionTypeInstance)将配置部分(使用.GetSection("MySection")检索)绑定到 object 。 这也有好处,它可以为您进行转换(请参阅示例中的整数)。

示例 (NET 6)

appsettings.json

{
  "MySection": {
    "DefinedString": "yay, I'm defined",
    "DefinedInteger": 1337
  }
}

MySection.cs

// could also be a struct or readonly struct
public class MySectionType
{
  public string DefinedString { get; init; } = "default string";
  public int DefinedInteger { get; init; } = -1;
  public string OtherString { get; init; } = "default string";
  public int OtherInteger { get; init; } = -1;

  public override string ToString() => 
    $"defined string :   \"{DefinedString}\"\n" +
    $"defined integer:   {DefinedInteger}\n" +
    $"undefined string : \"{OtherString}\"\n" +
    $"undefined integer: {OtherInteger}";
}

程序.cs

ConfigurationManager configuration = GetYourConfigurationManagerHere();

// either
var mySection = configuration.GetSection("MySection").Get<MySectionType>();

// or
var mySection = new MySectionType();
configuration.GetSection("MySection").Bind(mySection);

Console.WriteLine(mySection);

// output:
// defined string :   "yay, I'm defined"
// defined integer:   1337
// undefined string : "default string"
// undefined integer: -1

我认为C:\\%WIN%\\ Microsoft.NET下的machine.config会这样做。 将密钥添加到该文件作为默认值。

http://msdn.microsoft.com/en-us/library/ms228154.aspx

您可以围绕ConfigurationManager构建逻辑,以获取检索应用程序设置值的键入方式。 在这里使用TypeDescriptor来转换值。

/// /// ConfigurationManager的实用方法///公共静态类ConfigurationManagerWrapper {

    /// <summary>
    /// Use this extension method to get a strongly typed app setting from the configuration file.
    /// Returns app setting in configuration file if key found and tries to convert the value to a specified type. In case this fails, the fallback value
    /// or if NOT specified - default value - of the app setting is returned
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="appsettingKey"></param>
    /// <param name="fallback"></param>
    /// <returns></returns>
    public static T GetAppsetting<T>(string appsettingKey, T fallback = default(T))
    {
        string val = ConfigurationManager.AppSettings[appsettingKey] ?? "";
        if (!string.IsNullOrEmpty(val))
        {
            try
            {
                Type typeDefault = typeof(T);
                var converter = TypeDescriptor.GetConverter(typeof(T));
                return converter.CanConvertFrom(typeof(string)) ? (T)converter.ConvertFrom(val) : fallback;
            }
            catch (Exception err)
            {
                Console.WriteLine(err); //Swallow exception
                return fallback;
            }
        }
        return fallback;
    }

}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM