ASP.NET 5(vNext) - 获取配置设置 [英] ASP.NET 5 (vNext) - Getting a Configuration Setting

查看:123
本文介绍了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"];

我将有code一样,在我的code洒线。如今,在世界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

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

从那里,我完全难倒。我有MyClass.cs在/src/Website/$c$c/Models/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;
  }
}

我如何获得的价值的AppSettings: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.

下面是一个例子:<一href=\"https://github.com/aspnet/Options/blob/a3b972c8e2a43f5f99a0a7ce23dfa131af1e29a4/test/Microsoft.Extensions.Options.Test/OptionsTest.cs#L84-L87\" rel=\"nofollow\">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);

这样,你就不必从担心那里的设定来源于,它是如何存储,或有什么结构。您只需predefine你的选择模型和奇迹发生。

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) - 获取配置设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆