十二個 ASP.NET Core 例子——配置操做

  目錄:html

  1. 簡單配置(利用configration 鍵值讀取)
  2. 使用選項和配置對象(自定義類綁定配置文件實現讀取)
  3. IOptionsSnapshot(配置文件更改時也變化)
  4. 內存數據放到配置對象中
  5. 實體框架自定義配置
  6. CommandLine配置(利用命令行配置)

     注:這是院子裏面大神提供的例子。傳送門sql


 

  1.簡單配置(利用configration 鍵值讀取)數據庫

  注意點多級節點用「:」冒號json

        public static IConfigurationRoot Configuration { get; set; }//吐槽沒有開放出來。每次都要new

        public HomeController()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
            Configuration = builder.Build();
            var value = Configuration["option1"];//一級節點
            var value2 = Configuration["Logging:IncludeScopes"];//二級節點
            var value3 = Configuration["Logging:LogLevel:Default"];//三級節點
            var value4 = Configuration["Patients:1:Name"];//數據狀況下,去第二個元素的第一節點
        }
View Code

  appsettings.json 文件app

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-AspNetCoreAuthIdentity-c52f1669-ef35-4a6f-af80-47f83d0b7b98;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "option1": "value1_from_json",
  "option2": 2,
  "Patients": [
    {
      "Name": "Gandalf",
      "Age": "1000"
    },
    {
      "Name": "Harry",
      "Age": "17"
    }
  ]
}
View Code

    2.使用選項和配置對象(自定義類綁定配置文件實現讀取)框架

  建立本身的類。ide

    public class MyOptions
    {
        public MyOptions()
        {
            // Set default value.
            Option1 = "value1_from_ctor";
        }
        public string Option1 { get; set; }
        public int Option2 { get; set; } = 5;
    }
View Code

    項目啓動時注入到配置中Services.Configureui

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

            // Register the IConfiguration instance which MyOptions binds against.
            services.Configure<MyOptions>(Configuration);
        }
View Code

  獲取值spa

        private readonly MyOptions _options;

        public HomeController(IOptions<MyOptions> options)
        {
            _options = options.Value;
        }
View Code

 appsetting.json不用和類的字段徹底一致,只要包含就能夠了命令行

  3.IOptionsSnapshot(配置文件更改時也變化)

        private readonly MyOptions _options;

        public HomeController(IOptionsSnapshot<MyOptions> options)
        {
            _options = options.Value;
        }
View Code

IOptionsSnapshot的做用:在配置文件修改的時候,配置數據也會變化。(刷新頁面)

 4.內存數據放到配置對象中(AddInMemoryCollection)

        public static IConfigurationRoot Configuration { get; set; }
        public HomeController()
        {
            var dict = new Dictionary<string, string>
            {
                {"Profile:MachineName", "Rick"},
                {"App:MainWindow:Height", "11"},
                {"App:MainWindow:Width", "11"},
                {"App:MainWindow:Top", "11"},
                {"App:MainWindow:Left", "11"}
            };
            var builder = new ConfigurationBuilder();
            builder.AddInMemoryCollection(dict);
            Configuration = builder.Build();
            var vlaue = Configuration["Profile:MachineName"];
        }
View Code

顧名思義,不用去配置文件中讀取,能夠直接把內存中的數據放到配置對象中。【感受有點不必,既然在內存中,爲何不直接用】

這裏還講了一個GetValue<T>;做用:肯定配置的值類型,設置默認值。用法:Configuration.GetValue<int>("App:MainWindow:Left", 80);

 5.實體框架自定義配置(AddEntityFrameworkConfig)

利用EF讀取數據庫讀取數據和寫入數據。 相似利用EF 對數據庫數據操做。

1.建立實體類 2.建立DbContext 3.建立自定義配置提供程序EFConfigProvider,4.建立資源給Provider,5.AddEntityFrameworkConfig 6.讀取

代碼較多操做較多就不貼了。。

 6.CommandLine配置(AddCommandLine)命令行配置

先添加引用「Microsoft.Extensions.Configuration.CommandLine」

控制檯類型下,添加命令行參數

        public static IConfigurationRoot Configuration { get; set; }

        public static Dictionary<string, string> GetSwitchMappings(
            IReadOnlyDictionary<string, string> configurationStrings)
        {
            return configurationStrings.Select(item =>
                    new KeyValuePair<string, string>(
                        "-" + item.Key.Substring(item.Key.LastIndexOf(':') + 1),
                        item.Key))
                .ToDictionary(
                    item => item.Key, item => item.Value);
        }
        public static void Main(string[] args = null)
        {
            var dict = new Dictionary<string, string>
            {
                {"Profile:MachineName", "Rick"},
                {"App:MainWindow:Left", "11"}
            };
            var builder = new ConfigurationBuilder();
            builder.AddInMemoryCollection(dict)
                .AddCommandLine(args, GetSwitchMappings(dict));
            Configuration = builder.Build();
            Console.WriteLine($"Hello {Configuration["Profile:MachineName"]}");

            // Set the default value to 80
            var left = Configuration.GetValue<int>("App:MainWindow:Left", 80);
            Console.WriteLine($"Left {left}");
            Console.ReadKey();
        }
View Code

注意:命令行參數有必定的格式,也能夠利用GetSwitchMappings自定義格式。

相關文章
相關標籤/搜索