本文介绍了ASP.NET 5 (vNext) - 获取配置设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基本的应用程序来学习 ASP.NET 5.我发现非常令人困惑的一个领域是配置.在 ASP.NET 5 之前,我可以执行以下操作:

I'm writing a basic app to learn ASP.NET 5. One area I find very confusing is configuration. Prior to ASP.NET 5, I could do the following:

var settingValue = ConfigurationManager.AppSettings["SomeKey"];

我会在我的代码中散布这样的代码行.现在,在 vNext 世界中,我有一个如下所示的 config.json 文件:

I would have lines of code like that sprinkled throughout my code. Now, in the vNext world, I have a config.json file that looks like this:

config.json

{
  "AppSettings": {
    "SomeKey":"SomeValue"
  }
}

然后在 Startup.cs 中,我有以下内容:Startup.cs

Then in Startup.cs, I have the following:Startup.cs

public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment environment)
{
  Configuration = new Configuration()
      .AddJsonFile("config.json");
}

从那里开始,我完全被难住了.我在/src/Website/Code/Models/MyClass.cs 中有 MyClass.cs.

From there, I'm totally stumped. I have MyClass.cs in /src/Website/Code/Models/MyClass.cs.

MyClass.cs

public class MyClass
{
  public string DoSomething()
  {
    var result = string.Empty;
    var keyValue = string.Empty; // TODO: What do I do here? How do I get the value of "AppSettings:SomeKey"?
    return result;
  }
}

如何获取Ap​​pSettings:SomeKey"的值?

How do I get the value of "AppSettings:SomeKey"?

推荐答案

我强烈建议使用 OptionsModel 而不是直接读取配置.它允许将强类型模型绑定到配置.

I highly recommend using the OptionsModel instead of reading the configuration directly. It allows strong typed model binding to configuration.

这是一个例子:GitHub.com/aspnet/Options/test/Microsoft.Extensions.Options.Test/OptionsTest.cs

为您的特定情况创建一个模型:

For your particular case create a model:

class AppSettings {
    public string SomeSetting {get;set;}
}

然后将其绑定到您的配置:

and then bind it to your configuration:

var config = // The configuration object
var options = ConfigurationBinder.Bind<AppSettings>(config);
Console.WriteLine(options.SomeSetting);

这样您就不必担心设置的来源、存储方式或结构.您只需预先定义您的选项模型,奇迹就会发生.

That way you don't have to worry from where the setting comes from, how it is stored or what is the structure. You simply predefine your options model and magic happens.

这篇关于ASP.NET 5 (vNext) - 获取配置设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 03:55