在.net core中使用配置文件的幾個示例和方法

原文連接:blog.zhuliang.ltd/back-end/co…web

如下示例基於 .net core 2.2json

ASP.NET MVC示例

asp.net mvc已經內部實現了對配置appsettings.json文件的使用,builder默認支持熱更新。數組

使用示例:

假設appsettings.json內容爲:mvc

{
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
複製代碼
  1. 新建一個跟appsettings.json結構保持一致的類,如:
namespace webapp.Models
    {
        public class AppsettingsModel
        {
            public Logging Logging { get; set; }

            public string AllowedHosts { get; set; }
        }

        public class Logging
        {
            public LogLevel LogLevel { get; set; }
        }

        public class LogLevel
        {
            public string Default { get; set; }
        }
    }
複製代碼
  1. 在Startup.cs中進行依賴注入
public void ConfigureServices(IServiceCollection services) {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            // 依賴注入
            services.Configure<AppsettingsModel>(Configuration);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
複製代碼
  1. 在controller中調用:
public class TestController : Controller
    {
        private readonly AppsettingsModel _appsettingsModel;
        //若要使用熱更新,則入參調整爲 IOptionsSnapshot<T>
        public TestController(IOptions<AppsettingsModel> appsettingsModel) {
            _appsettingsModel = appsettingsModel.Value;
        }

        public IActionResult Index() {
            return View("Index", _appsettingsModel.Logging.LogLevel.Default);
        }
    }
複製代碼

如何覆寫默認行爲?如取消熱更新支持,方法以下:

假設測試controller爲app

public class TestController : Controller
    {
        private readonly AppsettingsModel _appsettingsModel;
        //使用的是:IOptionsSnapshot<T>
        public TestController(IOptionsSnapshot<AppsettingsModel> appsettingsModel) {
            _appsettingsModel = appsettingsModel.Value;
        }

        public IActionResult Index() {
            return View("Index", _appsettingsModel.Logging.LogLevel.Default);
        }
    }
複製代碼
public class Program
    {
        public static void Main(string[] args) {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) => //1.經過該方法來覆蓋配置
                {
                    //2.從新添加json配置文件
                    config.AddJsonFile("appsettings.json", false, false); //3.最後一個參數就是是否熱更新的布爾值
                })
                .UseStartup<Startup>();
    }
複製代碼

853140e9-c2ae-448b-9564-59e27023f387.png

  • 這個時候,人爲將熱更新給關閉了,此時更新json文件後,修改後的內容不會更新到系統中。

控制檯示例

對於console項目,默認是沒有這個dll的,須要自行從nuget安裝asp.net

從nuget中安裝:Microsoft.AspNetCore.All (注意,末尾不是dll,而是all)webapp

在項目中引入:Microsoft.Extensions.Configuration; 並使用ConfigurationBuilder來構建配置。測試

使用應用程序參數

在控制檯項目屬性中增長name和class參數:ui

e4c2f50f-6d3d-4867-b12e-e2a3ede38da9.png

使用:spa

class Program
{
    static void Main(string[] args) {
        var builder = new ConfigurationBuilder()
            .AddCommandLine(args);
        var configuration = builder.Build();

        Console.WriteLine($"name:{configuration["name"]}"); //name:CLS
        Console.WriteLine($"class:{configuration["class"]}");   //class:Class_A

        Console.Read();
    }
}
複製代碼

使用鍵值對枚舉(這裏以字典來講明)

class Program
    {
                static void Main(string[] args) {
                    var dict = new Dictionary<string, string>
                    {
                        {"name","MC"},
                        {"class","CLASS_MC"}
                    };
                    var builder = new ConfigurationBuilder()
// .AddCommandLine(args)
                    .AddInMemoryCollection(dict);
        
                    var configuration = builder.Build();
        
                    Console.WriteLine($"name:{configuration["name"]}");//name:MC
                    Console.WriteLine($"class:{configuration["class"]}");  //class:CLASS_MC
        
                    Console.Read();
                }
    }
複製代碼

注意事項:

  • 這裏須要注意下,雖然 AddCommandLine 和 AddInMemoryCollection 能夠同時調用,但不一樣的使用次序,效果是不同的(後一個會覆蓋前一個的內容---淺覆蓋),如:
/* 假設 在項目屬性中,定義的內容爲:name=CLS,class=CLASS_CLS,grade="mygrade" 在代碼中,dict的內容爲:name=MC,class=CLASS_MC */
//對於代碼:
var builder = new ConfigurationBuilder()
                    .AddCommandLine(args)
                    .AddInMemoryCollection(dict);
                    var configuration = builder.Build();
        
                    Console.WriteLine($"name:{configuration["name"]}");//name:MC
                    Console.WriteLine($"class:{configuration["class"]}");  //class:CLASS_MC
                    Console.WriteLine($"grade:{configuration["grade"]}");  //grade:mygrade
                    
//對於代碼:
var builder = new ConfigurationBuilder()                    
                    .AddInMemoryCollection(dict)
                    .AddCommandLine(args);
                    var configuration = builder.Build();
        
                    Console.WriteLine($"name:{configuration["name"]}");//name:CLS
                    Console.WriteLine($"class:{configuration["class"]}");  //class:CLASS_CLS
                    Console.WriteLine($"grade:{configuration["grade"]}");  //grade:mygrade

複製代碼
  • 另外,須要注意,若是用dotnet命令來執行CommandLineSample.dll,那麼「應用程序參數」須要直接跟在命令的後面,如:
    • 另外若是AddInMemoryCollection和AddCommandLine同時使用,那麼須要將AddCommandLine最後調用,不然一旦被覆蓋了,再用dotnet來調用,會沒有效果。
dotnet   CommandLineSample.dll   name=111 class=222  grade="my grade"
複製代碼

使用JSON文件

  • 在項目根目錄建立「jsconfig1.json」,同時修改該文件的屬性:
    • 複製到輸出目錄:始終複製
    • 生成操做:內容

JSON文件內容:

{
      "Class": "Class A",
      "PersonInfo": {
            "name": "my name",
            "age": "12"
      },
      "Hobbies": [
            {
                  "Type": "Family",
                  "HobbyName": "Piano"
            },
            {
                  "Type": "Personal",
                  "HobbyName": "Singing"
            }
      ]
}
複製代碼
static void Main(string[] args) {
    var builder = new ConfigurationBuilder()
        .AddJsonFile("jsconfig1.json");

    var configuration = builder.Build();

    Console.WriteLine($"name:{configuration["PersonInfo:name"]}");
    Console.WriteLine($"class:{configuration["class"]}");
    Console.WriteLine($"age:{configuration["PersonInfo:age"]}");
    //注意下調用參數時的格式:"{參數Key}:{數組索引}:{子項參數Key}"
    Console.WriteLine($"FamilyHobby:{configuration["Hobbies:0:HobbyName"]}");
    Console.WriteLine($"PersonalHobby:{configuration["Hobbies:1:HobbyName"]}");

    Console.Read();
}
複製代碼
相關文章
相關標籤/搜索