AppSettings 后备/默认值?

发布于 2024-09-24 12:24:52 字数 276 浏览 0 评论 0原文

ASP.NET

对于我使用的每个 appSetting,我想指定一个值,如果在 appSettings 中找不到指定的键,则将返回该值。我本来打算创建一个类来管理它,但我想这个功能可能已经在 .NET Framework 中的某个地方了?

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

如果有,我可以在调用它之前(从不同的地方)将 appSettings 放入该类型的对象中。

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. I was about to create a class to manage this, but I'm thinking this functionality is probably already in the .NET Framework somewhere?

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?

If there is, I could put the appSettings into an object of that type before calling into it (from various places).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

千笙结 2024-10-01 12:24:52

这就是我所做的。

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

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

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

This is what I do.

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

For Boolean and other non-string types...

bool.Parse(WebConfigurationManager.AppSettings["MyBoolean"] ?? "false")
对不⑦ 2024-10-01 12:24:52

ASP.NET 的 ConfigurationManager 提供了该功能。您可以使用 .Get().Bind( 将配置节(通过 .GetSection("MySection") 检索)绑定到对象mySectionTypeInstance)。这还有一个好处,它可以为您进行转换(请参阅示例中的整数)。

示例 (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}";
}

Program.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

ASP.NET's ConfigurationManager provides that functionality. You can bind your configuration section (retrieved with .GetSection("MySection")) to an object with either .Get<MySectionType>() or .Bind(mySectionTypeInstance). This also has the benefit, that it does conversion for you (see integers in the example).

Example (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() => 
    
quot;defined string :   \"{DefinedString}\"\n" +
    
quot;defined integer:   {DefinedInteger}\n" +
    
quot;undefined string : \"{OtherString}\"\n" +
    
quot;undefined integer: {OtherInteger}";
}

Program.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
说谎友 2024-10-01 12:24:52

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

您可以创建一个基于 Dictionary 的类,该类提供 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;
        }
    }
}

字符串而不是保持通用。

还有 DependencyObject 来自Silverlight 和 WPF 世界(如果有的话)。

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

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

key 可以是字符串索引器上的 null。但我知道在多个地方这样做很痛苦。

I don't believe there's anything built into .NET which provides the functionality you're looking for.

You could create a class based on Dictionary<TKey, TValue> that provides an overload of TryGetValue with an additional argument for a default value, e.g.:

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 strings instead of keeping in generic.

There's also DependencyObject from the Silverlight and WPF world if those are options.

Of course, the simplest way is something like this with a NameValueCollection:

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

key can be null on the string indexer. But I understand it's a pain to do that in multiple places.

她说她爱他 2024-10-01 12:24:52

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

You can make a custom configuration section and provide default values using the DefaultValue attribute. Instructions for that are available here.

世态炎凉 2024-10-01 12:24:52

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

/// <summary>
/// Utility methods for ConfigurationManager
/// </summary>
public static class 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>
    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;
    }
}

You can build logic around ConfigurationManager to get a typed way to retrieve your app setting value. Using here TypeDescriptor to convert value.

/// <summary>
/// Utility methods for ConfigurationManager
/// </summary>
public static class 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>
    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;
    }
}
我只土不豪 2024-10-01 12:24:52

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

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

I think the machine.config under C:\%WIN%\Microsoft.NET will do this. Add keys to that file as your default values.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文