日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > asp.net >内容正文

asp.net

ASP.NET Core中的配置

發(fā)布時(shí)間:2025/5/22 asp.net 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Core中的配置 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

配置

參考文件點(diǎn)擊跳轉(zhuǎn)

配置來(lái)源

  • 命令行參數(shù)
  • 自定義提供程序
  • 目錄文件
  • 環(huán)境變量
  • 內(nèi)存中的.NET 對(duì)象
  • 文件

    默認(rèn)配置

  • CreateDefaultBuilder方法提供有默認(rèn)配置,在這個(gè)方法中會(huì)接收前綴為ASPNETCORE_的變量和命令行參數(shù)以及appsettings.json和appsettings.{Environment}.json等,可以通過(guò)下面的源碼看到,注意配置文件的順序
  • 一般順序?yàn)?/li>
  • 文件
  • Azure
  • 用戶機(jī)密(生產(chǎn)中沒(méi)有)
  • 環(huán)境變量
  • 命令行參數(shù)
  • 命令行參數(shù)可以更新替換相關(guān)的程序設(shè)置,與前面提到的順序有關(guān),詳細(xì)見下面的約定

    public static IWebHostBuilder CreateDefaultBuilder(string[] args){var builder = new WebHostBuilder();if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey))){builder.UseContentRoot(Directory.GetCurrentDirectory());}if (args != null){builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());}builder.UseKestrel((builderContext, options) =>{options.Configure(builderContext.Configuration.GetSection("Kestrel"));}).ConfigureAppConfiguration((hostingContext, config) =>{var env = hostingContext.HostingEnvironment;config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);if (env.IsDevelopment()){var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));if (appAssembly != null){config.AddUserSecrets(appAssembly, optional: true);}}config.AddEnvironmentVariables();if (args != null){config.AddCommandLine(args);}}).ConfigureLogging((hostingContext, logging) =>{logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));logging.AddConsole();logging.AddDebug();logging.AddEventSourceLogger();}).ConfigureServices((hostingContext, services) =>{// Fallbackservices.PostConfigure<HostFilteringOptions>(options =>{if (options.AllowedHosts == null || options.AllowedHosts.Count == 0){// "AllowedHosts": "localhost;127.0.0.1;[::1]"var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);// Fall back to "*" to disable.options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });}});// Change notificationservices.AddSingleton<IOptionsChangeTokenSource<HostFilteringOptions>>(new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration));services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();}).UseIIS().UseIISIntegration().UseDefaultServiceProvider((context, options) =>{options.ValidateScopes = context.HostingEnvironment.IsDevelopment();});return builder;}

    相關(guān)約定

    • 鍵不區(qū)分大小寫,但是linux好像區(qū)分,所以最好還是有區(qū)分的好
    • 同鍵值會(huì)被覆蓋,以最后的為準(zhǔn)
    • 環(huán)境變量中,冒號(hào)分隔不適應(yīng)用所有的平臺(tái),但是雙下劃線支持所有的平臺(tái)
    • Azure中用兩個(gè)破折號(hào),國(guó)內(nèi)有阿里的比較多
    • ConfigurationBinder支持配置到對(duì)象的轉(zhuǎn)換,有Bind和Get<>的兩種方式,注意區(qū)分,建議用Get
    • 值是字符串且NULL不能出現(xiàn)在配置文件中也不能綁定到相應(yīng)的對(duì)象中去

      參數(shù)提供程序

      主機(jī)通過(guò)ConfigureAppConfiguration指定應(yīng)用配置程序

      命令行參數(shù)提供程序

      配置
    • 其實(shí)CreateDefaultBuider已經(jīng)支持了,但是如果需要應(yīng)用程序配置并能實(shí)現(xiàn)覆蓋的功能就需要在CnfigureAppConfiguration中添加并且在最后添加AddCommandLine如下:
    //一種寫法 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{// Call other providers here and call AddCommandLine last.config.AddCommandLine(args);}).UseStartup<Startup>(); //另一種寫法 var config = new ConfigurationBuilder()// Call additional providers here as needed.// Call AddCommandLine last to allow arguments to override other configuration..AddCommandLine(args).Build();var host = new WebHostBuilder().UseConfiguration(config).UseKestrel().UseStartup<Startup>();
    使用
    • 命令行后有兩種賦值方式,等號(hào)和空格(鍵前必順有--或/),不要混合使用(知道的多不是讓你亂用的,你的明白)
    • 等號(hào)賦值 值可以為null
    dotnet run CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 dotnet run --CommandLineKey1 value1 /CommandLineKey2 value2 dotnet run CommandLineKey1= CommandLineKey2=value2
    • 交換映射
      就是給命令行的鍵值改名,以-開頭的必順要交換,再加上默認(rèn)提供程序沒(méi)有注入的地方,如果硬傳將造成格式異常,所以可以通過(guò)AddCommandLine在ConfigureAppConfiguration中進(jìn)行傳遞
    public static readonly Dictionary<string, string> _switchMappings = new Dictionary<string, string>{{ "-CLKey1", "CommandLineKey1" },{ "-CLKey2", "CommandLineKey2" }};WebHost.CreateDefaultBuilder().ConfigureAppConfiguration((hostingContext, config) =>{config.AddCommandLine(args, _switchMappings);}).UseStartup<Startup>();

    環(huán)境變量提供程序

    注意:分隔無(wú)法適應(yīng)所有的平臺(tái),__可以,由加載順序可以知道環(huán)境變量是可以替換appsettings文件中的配置,注意默認(rèn)的環(huán)境變量前綴是ASPNETCORE_所以為了區(qū)分自己添加的不要用這個(gè)前綴了,前綴盡量見名知義,一個(gè)結(jié)果 就是能自解

    配置

    與命令行一樣在ConfigureAppConfiguration中添加并聲明前綴,如下:

    WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{// Call additional providers here as needed.// Call AddEnvironmentVariables last if you need to allow environment// variables to override values from other providers.config.AddEnvironmentVariables(prefix: "PREFIX_");}).UseStartup<Startup>(); //二種寫法 var config = new ConfigurationBuilder().AddEnvironmentVariables().Build();var host = new WebHostBuilder().UseConfiguration(config).UseKestrel().UseStartup<Startup>();
    使用

    就是配置系統(tǒng)級(jí)的環(huán)境變量,不同的系統(tǒng)不太一樣,windows可以在屬性->環(huán)境變境中找到,linux可以命令行配置也可以直接改文件

    文件配置提供程序(重點(diǎn),重點(diǎn),使用比較多)

    首先明白不論何種文件,一定要能根據(jù)路徑找到,所以我們一定要通過(guò)SetBasePath設(shè)置基路徑,然后再是不同的文件

    INI文件

    配置

    與前面的一樣也是在ConfigureAppConfiguration中添加

    WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{config.SetBasePath(Directory.GetCurrentDirectory());config.AddIniFile("config.ini", optional: true, reloadOnChange: true);}).UseStartup<Startup>(); //二種 var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddIniFile("config.ini", optional: true, reloadOnChange: true).Build();var host = new WebHostBuilder().UseConfiguration(config).UseKestrel().UseStartup<Startup>();

    JSON文件

    配置
    WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{config.SetBasePath(Directory.GetCurrentDirectory());config.AddJsonFile("config.json", optional: true, reloadOnChange: true);}).UseStartup<Startup>(); //二種 var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("config.json", optional: true, reloadOnChange: true).Build();var host = new WebHostBuilder().UseConfiguration(config).UseKestrel().UseStartup<Startup>();

    XML文件

    配置
    WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{config.SetBasePath(Directory.GetCurrentDirectory());config.AddXmlFile("config.xml", optional: true, reloadOnChange: true);}).UseStartup<Startup>(); //另一種寫法(二種) var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddXmlFile("config.xml", optional: true, reloadOnChange: true).Build();var host = new WebHostBuilder().UseConfiguration(config).UseKestrel().UseStartup<Startup>();

    Key-pre-file配置提供程序

    使用目錄的文件作為配置,鍵是文件名,值是包含在文件的內(nèi)容。路徑必順是絕對(duì)路徑。雙下劃線字符 (__) 用作文件名中的配置鍵分隔符。 例如,文件名 Logging__LogLevel__System 生成配置鍵 Logging:LogLevel:System

    配置
    WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{config.SetBasePath(Directory.GetCurrentDirectory());var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files");config.AddKeyPerFile(directoryPath: path, optional: true);}).UseStartup<Startup>(); //二種 var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files"); var config = new ConfigurationBuilder().AddKeyPerFile(directoryPath: path, optional: true).Build();var host = new WebHostBuilder().UseConfiguration(config).UseKestrel().UseStartup<Startup>();

    內(nèi)存配置提供程序

    就是內(nèi)存中的對(duì)象(字典對(duì)象之流)結(jié)構(gòu)為IEnumerable<KeyValuePair<String,String>>

    配置
    public static readonly Dictionary<string, string> _dict = new Dictionary<string, string>{{"MemoryCollectionKey1", "value1"},{"MemoryCollectionKey2", "value2"}}; WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{config.AddInMemoryCollection(_dict);}).UseStartup<Startup>(); //二種 var dict = new Dictionary<string, string>{{"MemoryCollectionKey1", "value1"},{"MemoryCollectionKey2", "value2"}};var config = new ConfigurationBuilder().AddInMemoryCollection(dict).Build();var host = new WebHostBuilder().UseConfiguration(config).UseKestrel().UseStartup<Startup>();

    獲取配置內(nèi)容

    • GetSection 獲取指定子節(jié)鍵提取值
    • GetChildren 獲取節(jié)點(diǎn)的值
    • Bind 把字符串構(gòu)造為POCO對(duì)象
    • Get 綁定并返回指定類型 Get 比使用 Bind 更方便

    綁定是按約定提供的。 不需要自定義配置提供程序?qū)崿F(xiàn)數(shù)組綁定。

    可以在代碼中讀到相應(yīng)的值

    var configEntryFilter = new string[] { "ASPNETCORE_", "urls", "Logging", "ENVIRONMENT", "contentRoot", "AllowedHosts", "applicationName", "CommandLine" };var config = cfg.AsEnumerable();FilteredConfiguration = config.Where(kvp => config.Any(i => configEntryFilter.Any(prefix => kvp.Key.StartsWith(prefix))));var starship = new Starship();cfg.GetSection("starship").Bind(starship);Starship = starship;TvShow = cfg.GetSection("tvshow").Get<TvShow>();ArrayExample = cfg.GetSection("array").Get<ArrayExample>();JsonArrayExample = cfg.GetSection("json_array").Get<JsonArrayExample>();Customer customer = cfg.GetSection("customer").Get<Customer>();var value1 = cfg.GetValue<object>("name", "read error");

    自定義配置提供程序

    該示例應(yīng)用演示了如何使用實(shí)體框架 (EF) 創(chuàng)建從數(shù)據(jù)庫(kù)讀取配置鍵值對(duì)的基本配置提供程序。
    倒著分析(正分析看官文)

    • 我們要添加一個(gè)配置到ConfigurationBuilder中(可以用擴(kuò)展 AddEFConfiguration)
    • 要擴(kuò)展我們要有配置內(nèi)容類來(lái)作為載體EFConfigurationContext
    • 我們要用對(duì)應(yīng)的內(nèi)容解析類來(lái)提供解析 EFConfigurationProvider
    • 最后我們要有解析出來(lái)對(duì)應(yīng)的對(duì)象來(lái)進(jìn)行綁定 EFConfigurationValue

    -最后我們要注入到ConfigureServices和Configure中這樣就可以在指定的作用域內(nèi)使用了
    詳見我抄官網(wǎng)上的git源碼點(diǎn)擊跳轉(zhuǎn),同樣官網(wǎng)上的源碼也是可以運(yùn)行的。

    轉(zhuǎn)載于:https://www.cnblogs.com/ants_double/p/10511863.html

    總結(jié)

    以上是生活随笔為你收集整理的ASP.NET Core中的配置的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。