ASP .Net Core appsettings.json获取配置值正确而简单的方法

2021-11-12  乐帮网

netcore

实现忍不住要说一下在ASP .Net Core中从appsettings.json中获取值。网上都是一片乱说,基本都没有写到点子上,人家框架里封装的好好的,非要自己画蛇添足,扩展方法。我列举一下几种常见的用法,就以Startup类为例吧。假设appsetting.json内容如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "urls": "http://*:8000",
"key1","testvalue",
"user": {
    "name": "小红",
    "age": 23
  }
}

1、简的获取


public class Startup{
 public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration = configuration;
            Environment = env;
        }
  public void ConfigureServices(IServiceCollection services){
 	var str = Configuration.GetValue(typeof(string),"key");
            var str2 = Configuration.GetValue<string>("key");
}

}

以上两行已经打败90%以上文章。

2、嵌套获取

var name = Configuration.GetValue<string>("user:name");

3、强类型获取

public class User{
	public string name {get;set;}
	public uint age {get;set;}
}

var user = Configuration.GetValue<User>("user");

没有见过这么 简单的使用,最后说的是别忘了引入命名空间:  using Microsoft.Extensions.Configuration;

最后说一下如果在unit中测试模拟获取值,我们可以写这样的一个类来实现

namespace Microsoft.Extensions.Configuration
{
    /// <summary>
    /// Static helper class that allows binding strongly typed objects to configuration values.
    /// </summary>
    public static class ConfigurationBinder
    {
	...
        /// <summary>
        /// Extracts the value with the specified key and converts it to type T.
        /// </summary>
        /// <typeparam name="T">The type to convert the value to.</typeparam>
        /// <param name="configuration">The configuration.</param>
        /// <param name="key">The key of the configuration section's value to convert.</param>
        /// <returns>The converted value.</returns>
        public static T GetValue<T>(this IConfiguration configuration, string key)
        {
            return GetValue(configuration, key, default(T));
        }

        /// <summary>
        /// Extracts the value with the specified key and converts it to type T.
        /// </summary>
        /// <typeparam name="T">The type to convert the value to.</typeparam>
        /// <param name="configuration">The configuration.</param>
        /// <param name="key">The key of the configuration section's value to convert.</param>
        /// <param name="defaultValue">The default value to use if no value is found.</param>
        /// <returns>The converted value.</returns>
        public static T GetValue<T>(this IConfiguration configuration, string key, T defaultValue)
        {
            return (T)GetValue(configuration, typeof(T), key, defaultValue);
        }

        /// <summary>
        /// Extracts the value with the specified key and converts it to the specified type.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="type">The type to convert the value to.</param>
        /// <param name="key">The key of the configuration section's value to convert.</param>
        /// <returns>The converted value.</returns>
        public static object GetValue(this IConfiguration configuration, Type type, string key)
        {
            return GetValue(configuration, type, key, defaultValue: null);
        }

        /// <summary>
        /// Extracts the value with the specified key and converts it to the specified type.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="type">The type to convert the value to.</param>
        /// <param name="key">The key of the configuration section's value to convert.</param>
        /// <param name="defaultValue">The default value to use if no value is found.</param>
        /// <returns>The converted value.</returns>
        public static object GetValue(this IConfiguration configuration, Type type, string key, object defaultValue)
        {
            var value = configuration.GetSection(key).Value;
            if (value != null)
            {
                return ConvertValue(type, value);
            }
            return defaultValue;
        }

    }
}
    

写在最后:如果你的项目类型并不是常见的.net core程序,不方便引入它的config模块,也可以竟然使用 Binder 模块,虽然这个不常见。

Microsoft.Extensions.Configuration    
Microsoft.Extensions.Configuration.Binder

公众号二维码

关注我的微信公众号
在公众号里留言交流
投稿邮箱:1052839972@qq.com

庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。

欧阳修

付款二维码

如果感觉对您有帮助
欢迎向作者提供捐赠
这将是创作的最大动力