简体   繁体   English

AppSettings 后备/默认值?

[英]AppSettings fallback/default value?

ASP.NET ASP.NET

For each appSetting I use, I want to specify a value that will be returned if the specified key isn't found in the appSettings.对于我使用的每个 appSetting,我想指定一个值,如果在 appSettings 中找不到指定的键,将返回该值。 I was about to create a class to manage this, but I'm thinking this functionality is probably already in the .NET Framework somewhere?我正要创建一个 class 来管理这个,但我认为这个功能可能已经在 .NET 框架的某个地方?

Is there a NameValueCollection/Hash/etc-type class in .NET that will let me specify a key and a fallback/default value -- and return either the key's value, or the specified value? .NET 中是否有 NameValueCollection/Hash/etc-type class 可以让我指定一个键和一个后备/默认值 - 并返回键的值或指定的值?

If there is, I could put the appSettings into an object of that type before calling into it (from various places).如果有,我可以将 appSettings 放入该类型的 object 中,然后再调用它(从各个地方)。

I don't believe there's anything built into .NET which provides the functionality you're looking for. 我不相信.NET内置任何内容可以提供您正在寻找的功能。

You could create a class based on Dictionary<TKey, TValue> that provides an overload of TryGetValue with an additional argument for a default value, eg: 您可以创建一个基于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;
        }
    }
}

You could probably get away with string s instead of keeping in generic. 您可能可以使用string s而不是保持通用。

There's also DependencyObject from the Silverlight and WPF world if those are options. 如果这些是选项,那么还有来自Silverlight和WPF世界的DependencyObject

Of course, the simplest way is something like this with a NameValueCollection : 当然,最简单的方法是使用NameValueCollection

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

key can be null on the string indexer. key在字符串索引器上可以为null But I understand it's a pain to do that in multiple places. 但我明白在多个地方做这件事很痛苦。

This is what I do. 这就是我的工作。

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

For Boolean and other non-string types... 对于布尔值和其他非字符串类型......

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

You can make a custom configuration section and provide default values using the DefaultValue attribute. 您可以创建自定义配置部分,并使用DefaultValue属性提供默认值。 Instructions for that are available here . 有关该说明,请点击此处

ASP.NET's ConfigurationManager provides that functionality. ASP.NET 的 ConfigurationManager 提供了该功能。 You can bind your configuration section (retrieved with .GetSection("MySection") ) to an object with either .Get<MySectionType>() or .Bind(mySectionTypeInstance) .您可以使用.Get<MySectionType>().Bind(mySectionTypeInstance)将配置部分(使用.GetSection("MySection")检索)绑定到 object 。 This also has the benefit, that it does conversion for you (see integers in the example).这也有好处,它可以为您进行转换(请参阅示例中的整数)。

Example (NET 6)示例 (NET 6)

appsettings.json appsettings.json

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

MySection.cs 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}";
}

Program.cs程序.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

I think the machine.config under C:\\%WIN%\\Microsoft.NET will do this. 我认为C:\\%WIN%\\ Microsoft.NET下的machine.config会这样做。 Add keys to that file as your default values. 将密钥添加到该文件作为默认值。

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

You can build logic around ConfigurationManager to get a typed way to retrieve your app setting value. 您可以围绕ConfigurationManager构建逻辑,以获取检索应用程序设置值的键入方式。 Using here TypeDescriptor to convert value. 在这里使用TypeDescriptor来转换值。

/// /// Utility methods for ConfigurationManager /// public static class ConfigurationManagerWrapper { /// /// 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