简体   繁体   English

在 .NET 6 中访问配置的最佳方法是什么?

[英]What's the best method to access configuration in .NET 6?

The second answer of this question: ASP.NET Core 6 how to access Configuration during startup mentioned that we can access configuration in this way:这个问题的第二个答案: ASP.NET Core 6 如何在启动期间访问配置中提到我们可以通过这种方式访问​​配置:

A nice feature worth considering it to create a class that represents your settings and then bind the configuration to an instance of that class type.一个值得考虑的好功能是创建一个代表您的设置的类,然后将配置绑定到该类类型的实例。 For example, let's assume you create a new class called MyAppSettings with the same structure as your appSettings.json, you can do the following:例如,假设您创建了一个名为 MyAppSettings 的新类,其结构与您的 appSettings.json 相同,您可以执行以下操作:

var myAppSettings = builder.Configuration.Get<MyAppSettings>();
string logLevel = myAppSettings.Logging.LogLevel.Default;

I am confused about it and I want to know how to do that and what are the benefits of this.我对此感到困惑,我想知道如何做到这一点以及这样做有什么好处。

What's more, the best method to access configuration in .NET 6?此外,在 .NET 6 中访问配置的最佳方法是什么?


Explain my question in more detail.更详细地解释我的问题。 The appSetting.json file in my project has only one layer like this:我项目中的 appSetting.json 文件只有这样一层:

{
 "name": "jack",
 ...1000+,
 "age": "100"
}

So I cannot configure it using builder.congiguration.GetSection():所以我不能使用 builder.congiguration.GetSection() 来配置它:

builder.Services.Configure<XXX>(builder.Configuration.GetSection("XXX"));

How to configure it at once without changing the structure of appSettings.json?如何在不改变 appSettings.json 结构的情况下一次性配置?

thank you again~再次感谢~

You can refer to this simple demo to learn about how to您可以参考这个简单的演示来了解如何

create a class that represents your settings and then bind the configuration to an instance of that class type

The values in appsetting.json : appsetting.json中的值:

"UserCred": {
      "Username":"Jack",
      "Password":"123"
},

Create a model class:创建模型类:

public class User
{
    public string Username { get; set; }
    public string Password { get; set; }
}

Configure in your programs.cs :在您的programs.cs中配置:

builder.Services.Configure<User>(builder.Configuration.GetSection("UserCred"));

In the controller, use DI to inject it, then you can get the model with value:在控制器中,使用DI注入,就可以得到有值的模型:

public class HomeController : Controller
{
    private readonly IOptions<User> _configuration;

    public HomeController(IOptions<User> configuration)
    {
        _configuration = configuration;
    }

    //.......
}

在此处输入图像描述

What's the benefit?有什么好处?

For me, if there are many data ​​in appsetting.json , Creating a class to map them only needs to map once, You don't need to get them one by one, which makes coding more convenient.对我来说,如果appsetting.json中有很多数据,创建一个类来映射它们只需要映射一次,你不需要一个一个去获取,这样编码更方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM