First of all my main purpose is to setup the IP and Port for my application dynamically.
I'm using IConfiguration
to inject a json config file, like some tutorial mentioned.
However, I can't retrieve the configuration in Program.cs, because my WebHostBuilder
will use the StartUp and Url at the same time.
So at the time the host build up, there is nothing in my configuration.
WebProtocolSettings settings_Web = new WebProtocolSettings();
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseUrls(settings_Web.Url + ":" + settings_Web.Port)
.Build();
In 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);
}
My appsettings.json:
{
"WebProtocolSettings": {
"Url": "127.0.0.1",
"Port": 5050
}
}
My WebProtocolSettings.cs:
public class WebProtocolSettings
{
public string Url { get; set; }
public int Port { get; set; }
}
Adding the AppSettings.json file Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button. Once the File is created, it will have a DefaultConnection, below that a new AppSettings entry is added.
To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below.
Update .Net 6
It's now easy to get any settings from the ConfigurationManager by calling the GetValue<type>(string key) extension method. You can also use Index(string key) to return a string. See this answer.
You must build a configuration in your main method, get the section and bind it to your model. No way around it.
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();
}
##Update
An alternative way of doing it is by passing the configuration to UseConfiguration
as described in the
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();
}
or in ASP.NET Core > 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();
}
In .NET 6
var builder = WebApplication.CreateBuilder(args);
// Using the GetValue<type>(string key) method
var configValue = builder.Configuration.GetValue<string>("Authentication:CookieAuthentication:LoginPath");
// or using the index property (which always returns a string)
var configValue = builder.Configuration["Authentication:CookieAuthentication:LoginPath"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With