阅读Main Program.cs中的appsettings.json

时间:2017-01-19 09:54:56

标签: c# asp.net-core asp.net-core-1.0

首先,我的主要目的是动态设置应用程序的IP和端口。

我正在使用IConfiguration注入一个json配置文件,就像上面提到的一些教程一样。

但是,我无法在Program.cs中检索配置,因为我的WebHostBuilder会同时使用StartUp和Url。

所以在主机建立时,我的配置中没有任何内容。

WebProtocolSettings settings_Web = new WebProtocolSettings();
var host = new WebHostBuilder()
                .UseIISIntegration()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .UseUrls(settings_Web.Url + ":" + settings_Web.Port)
                .Build();

在Startup.cs

public Startup(IHostingEnvironment env)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{
    // Adds services required for using options.
    services.AddOptions();

    var _WebProtocolSettings = Configuration.GetSection("WebProtocolSettings");

    // Register the IConfiguration instance
    services.Configure<WebProtocolSettings>(_WebProtocolSettings);
}

我的appsettings.json:

{
    "WebProtocolSettings": {
        "Url": "127.0.0.1",
        "Port": 5050
    }
}

我的WebProtocolSettings.cs:

public class WebProtocolSettings
{
    public string Url { get; set; }
    public int Port { get; set; }
}

6 个答案:

答案 0 :(得分:35)

您必须在main方法中构建配置,获取该部分并将其绑定到您的模型。没办法。

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: false)
        .Build();

    WebProtocolSettings settings_Web = new WebProtocolSettings();
    config.GetSection("WebProtocolSettings").Bind(settings_Web);

    var host = new WebHostBuilder()
            .UseIISIntegration()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .UseUrls(settings_Web.Url + ":" + settings_Web.Port)
            .Build()

    host.Run();
}

更新

另一种方法是将配置传递给UseConfiguration,如

中所述
public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .AddCommandLine(args)
        .Build();

    var host = new WebHostBuilder()
        .UseUrls("http://*:5000")
        .UseConfiguration(config)
        .UseKestrel()
        .Configure(app =>
        {
            app.Run(context => 
                context.Response.WriteAsync("Hello, World!"));
        })
        .Build();

    host.Run();
}

或在ASP.NET Core&gt; 2.0

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .AddCommandLine(args)
        .Build();

    return WebHost.CreateDefaultBuilder(args)
        .UseUrls("http://*:5000")
        .UseConfiguration(config)
        .Configure(app =>
        {
            app.Run(context => 
                context.Response.WriteAsync("Hello, World!"));
        })
        .Build();
}

答案 1 :(得分:2)

在 asp.net core 3.1 中,您可以通过 hostContext 访问配置。此示例基于 Worker 服务项目:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    //Access configuration here with the Host Context.  For example, to get a connection string from AppSettings.json:
                    var connectionString = hostContext.Configuration.GetConnectionString("MyConnectionString");
                    services.AddHostedService<Worker>();
                });
    }

答案 2 :(得分:0)

.UseConfiguration(Tseng的替代答案)是最简单的方法,但是请注意,以这种方式配置时,在运行时对配置文件所做的更改不会应用于您的IConfiguration对象。要使配置保持动态,您必须使用.ConfigureAppConfiguration-但是您必须额外构建一次配置才能在Main()中使用。但是,您可以重复使用配置它的代码。

ASP.NET Core 2.2:

    public static void Main(string[] args)
    {
        IConfigurationBuilder configBuilderForMain = new ConfigurationBuilder();
        ConfigureConfiguration(configBuilderForMain);
        IConfiguration configForMain = configBuilderForMain.Build();

        // ... use configForMain to read config here ...

        var host = new WebHostBuilder()
            .ConfigureAppConfiguration(ConfigureConfiguration)
            // ... the rest of it ...
            .Build();
    }

    public static void ConfigureConfiguration(IConfigurationBuilder config)
    {
        config.SetBasePath(Directory.GetCurrentDirectory());
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    }

答案 3 :(得分:0)

具有支持命令行参数和默认appsettings文件的扩展方法:

public static class ConfigurationExtensions
{
    public static IConfigurationRoot BuildConfigurationRoot()
    {

        var args = Environment.GetCommandLineArgs();
        var envArg = args.IndexOf("--environment");
        var envFromArgs = envArg >= 0 ? args[envArg + 1] : null;

        var aspnetcore = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        var dotnetcore = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");

        var environment = envFromArgs ?? (string.IsNullOrWhiteSpace(aspnetcore)
            ? dotnetcore
            : aspnetcore);

        var configuration = new ConfigurationBuilder()
            .AddCommandLine(Environment.GetCommandLineArgs())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile(
                $"appsettings.{environment}.json",
                optional: true)
            .Build();

        return configuration; 
    }
}

答案 4 :(得分:-1)

在 .net core 3.1 中,您可以使用 ConfigurationHelper.GetConfiguration() 来获取 appSetting 变量:

appSettings.json

"Endpoint": {
"ip": "170.888.88.888",
"port": 88888}

程序.cs

public class Program
{
    public static void Main(string[] args)
    {
     var config = ConfigurationHelper.GetConfiguration();
     var ip = config["Endpoint:ip"];
     var port = config["Endpoint:port"];
    }
 }

答案 5 :(得分:-2)

使用此代码:

public class Program
{
    private static string _environmentName;

    public static void Main(string[] args)
    {
        var webHost = BuildWebHost(args);

        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile($"appsettings.{_environmentName}.json", optional: true, reloadOnChange: true)
            .AddCommandLine(args)
            .Build();

        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, config) =>
    {
        config.ClearProviders();
        _environmentName = hostingContext.HostingEnvironment.EnvironmentName;
    }).UseStartup<Startup>().Build();
}