繁体   English   中英

从1.0.0-rc1-final中的appsettings.json读取一个值

[英]Read a value from appsettings.json in 1.0.0-rc1-final

在我的一个具体课堂上。 我有方法。

public class Call : ICall
{
    ......
    public  Task<HttpResponseMessage> GetHttpResponseMessageFromDeviceAndDataService()
    {
        var client = new HttpClient();
        var uri = new Uri("http://localhost:30151");
        var response =  GetAsyncHttpResponseMessage(client, uri);
        return response;
    }

现在我将url放入appsettings.json。

{
    "AppSettings": {
       "uri": "http://localhost:30151"
    }
 }

我创建了一个Startup.cs

 public class Startup
{
    public IConfiguration Configuration { get; set; }
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
    }
}

现在我卡住了

编辑

顺便说一句,我没有控制器,它是一个控制台应用程序。

创建一个静态类

public static class AppSettings
{
    public static IConfiguration Configuration { get; set; }

    public static T Get<T>(string key)
    {
        if (Configuration == null)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            Configuration = configuration.GetSection("AppSettings");
        }

        return (T)Convert.ChangeType(Configuration[key], typeof(T));
    }
}

然后在任何地方访问设置

var uri = AppSettings.Get<string>("uri"); 
var rooms = AppSettings.Get<int>("noRooms");

appsettings.json示例

{
    "AppSettings": {
        "uri": "http://localhost:30151",
        "noRooms":  100
    }
}

从appSettings.json读取配置的首选方法是使用依赖注入和内置或(或第三方)IoC容器。 您只需将配置部分传递给Configure方法即可。

public class AppSettings
{
    public int NoRooms { get; set; }
    public string Uri { get; set; }
}

services.Configure<AppSettings>(Configuration.GetSection("appsettings"));

这样您就不必手动设置值或初始化AppSettings类。

并在您的服务中使用它:

public class Call : ICall
{
    private readonly AppSettings appSettings;

    public Call(IOptions<AppSettings> appSettings) 
    {
        this.appSettings = appSetings.Value;
    }

    public Task<HttpResponseMessage>GetHttpResponseMessageFromDeviceAndDataService()
    {
        var client = new HttpClient();
        var uri = new Uri(appSettings.Uri);
        var response =  GetAsyncHttpResponseMessage(client, uri);
        return response;
    }
}

IoC容器也可以在控制台应用程序中使用,您只需自己引导它。 ServiceCollection类没有依赖关系,可以正常实例化,当您完成配置后,将其转换为IServiceProvider并使用它解析主类,它将解析所有其他依赖项。

public class Program
{
    public static void Main(string[] args) 
    {
        var configurationBuilder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json");
        var configuration = configurationBuilder.Build()
            .ReloadOnChanged("appsettings.json");

        var services = new ServiceCollection();
        services.Configure<AppSettings>(configuration.GetSection("appsettings"));
        services.AddTransient<ICall, Call>();
        // add other services

        // after configuring, build the IoC container
        IServiceProvider provider = services.BuildServiceProvider();

        Program program = provider.GetService<Program>();

        // run the application, in a console application we got to wait synchronously
        program.Wait();
    }

    private readonly ICall callService;
    // your programs main entry point
    public Program(ICall callService) 
    {
        this.callService = callService;
    }

    public async Task Run()
    {
         HttpResponseMessage result = await call.GetHttpResponseMessageFromDeviceAndDataService();

         // do something with the result
    } 
}

您可以从IConfigurationRoot访问数据,如下所示:

Configuration["AppSettings:uri"]

像评论中建议的那样,我会将信息放在该信息的单独类中,并将其传递到DI容器中。

班级

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

DI

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(new AppSettings() { Uri = Configuration["AppSettings:uri"] });
    // ...
}

调节器

public class DemoController
{
    public HomeController(IOptions<AppSettings> settings) 
    {
       //do something with it
    }
}

暂无
暂无

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

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