.net 如何从 appsettings.json 获取价值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43757189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:54:56  来源:igfitidea点击:

how to get value from appsettings.json

.netappsettings

提问by ChiakiYu

public class Bar
{
    public static readonly string Foo = ConfigurationManager.AppSettings["Foo"];
}

In the .NET Framework 4.x, I can use the ConfigurationManager.AppSettings ["Foo"]to get Fooin Webconfig,and then I can easily get the value of Foothrough Bar.Foo

在.NET Framework 4.x中,我可以使用ConfigurationManager.AppSettings ["Foo"]get Fooin Webconfig,然后我可以很容易的获取Foothrough的值Bar.Foo

But in .Net core, I mustto inject options, And can not get the value of Foothrough Bar.Foo

但是在.Net核心中,我必须注入options,并且无法获得Foothrough的值Bar.Foo

Is there a method, which can be directly through the Bar.Footo get the value of Foo?

有没有一种方法,可以直接通过Bar.Foo来获取 的值 Foo

回答by MindingData

So there are really two ways to go about this.

所以真的有两种方法可以解决这个问题。

Option 1 : Options Class

选项 1:选项类

You have an appsettings.json file :

你有一个 appsettings.json 文件:

{
  "myConfiguration": {
    "myProperty": true 
  }
}

You create a Configuration POCO like so :

您可以像这样创建配置 POCO:

public class MyConfiguration
{
    public bool MyProperty { get; set; }
}

In your startup.cs you have something in your ConfigureServices that registers the configuration :

在您的 startup.cs 中,您的 ConfigureServices 中有一些内容用于注册配置:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MyConfiguration>(Configuration.GetSection("myConfiguration"));
}

Then in your controller/service you inject in the IOptions and it's useable.

然后在您的控制器/服务中注入 IOptions 并且它是可用的。

public class ValuesController : Controller
{
    private readonly MyConfiguration _myConfiguration;

    public ValuesController(IOptions<MyConfiguration> myConfiguration)
    {
        _myConfiguration = myConfiguration.Value;
    }
}

Personally I don't like using IOptions because I think it drags along some extra junk that I don't really want, but you can do cool things like hot swapping and stuff with it.

就我个人而言,我不喜欢使用 IOptions,因为我认为它会带来一些我并不真正想要的额外垃圾,但是您可以使用它来做一些很酷的事情,例如热插拔等。

Option 2 : Configuration POCO

选项 2:配置 POCO

It's mostly the same but in your Configure Services method you instead bind to a singleton of your POCO.

它大致相同,但在您的配置服务方法中,您改为绑定到 POCO 的单例。

public void ConfigureServices(IServiceCollection services)
{
    //services.Configure<MyConfiguration>(Configuration.GetSection("myConfiguration"));
    services.AddSingleton(Configuration.GetSection("myConfiguration").Get<MyConfiguration>());
}

And then you can just inject the POCO directly :

然后你可以直接注入 POCO:

public class ValuesController : Controller
{
    private readonly MyConfiguration _myConfiguration;

    public ValuesController(MyConfiguration myConfiguration)
    {
        _myConfiguration = myConfiguration;
    }
}

A little simplistic because you should probably use an interface to make unit testing a bit easier but you get the idea.

有点简单,因为您可能应该使用接口来使单元测试更容易一些,但您明白了。

Mostly taken from here : http://dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/

主要取自这里:http: //dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/

回答by Dave Shinkle

You can also use the configurationdirectly. Your settings are injected so you can get to them with DI...

也可以直接使用配置。您的设置已注入,因此您可以使用 DI 访问它们...

private readonly IConfiguration _configuration;

public MyClass(IConfiguration configuration)
{
    _configuration = configuration;
}

and then you can read your settings...

然后你可以阅读你的设置...

In this case I'm getting a collection back...

在这种情况下,我要取回一个集合...

var myList = _configuration.GetSection("MyList").Get<List<string>>();

回答by PinoyDev

The solutions on top are time consuming and not straightforward, this is the best effective way to do it, no setup needed on startup or anything. It's like using the good ol Configuration.Manager.AppSettings["setting"]

上面的解决方案既耗时又不简单,这是最有效的方法,无需在启动时进行设置或任何其他操作。这就像使用好的 ol Configuration.Manager.AppSettings["setting"]

First create a class like "Credential":

首先创建一个像“Credential”这样的类:

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

Now that's setup let put the IConfiguration on your constructor like so:

现在设置完成,让我们将 IConfiguration 放在您的构造函数上,如下所示:

    private IConfiguration _configuration;
    public ValuesController(IConfiguration iconfig)
    {
        _configuration = iconfig;
    }

Then you're ready to call it!

然后你就可以打电话了!

    Credential c = new Credential();
    c.UserName = _configuration.GetValue<string>("Credential:username");
    c.Password = _configuration.GetValue<string>("Credential:password");

Assuming your appsettings.json looks like this:

假设您的 appsettings.json 如下所示:

"Credential": {
    "username": "myuser",
    "password": "mypassword"
  }

Hope this helps somebody.

希望这可以帮助某人。

回答by pintu sharma

1.Add this in AppSettings.json file

1.在AppSettings.json文件中添加

"Swagger": { "Title": "API DEVELOPMENT" }

"Swagger": { "Title": "API 开发" }

2.then configure that in startup.cs file

2.然后在startup.cs文件中配置

public Startup(IConfiguration configuration) { Configuration = configuration; }

公共启动(IConfiguration配置){配置=配置;}

3.next public IConfiguration Configuration { get; }

3.next public IConfiguration Configuration { get; }

4.next get the value from appsettings.json

4.next 从 appsettings.json 获取值

var title = Configuration.GetSection("Swagger:Title").Value;

var title = Configuration.GetSection("Swagger:Title").Value;

5.and finally put here

5.最后放在这里

services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = title, Version = "v1" }); }

services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = title, Version = "v1" }); }