Could you please tell me how to get the value from an appsettings.json in the "Program.cs". If I start at the "Startup.cs" like this:
Model
class AppConfiguration
{
public string UrlProperty { get; set; }
}
Startup.cs
services.AddSingleton(Configuration.GetSection("Url").Get<AppConfiguration>());
Then go to the "Program.cs" and code it like so:
Program.cs
public static string Url { get; set; }
public static AppConfiguration configurtion { get; set; }
public Program(AppConfiguration configuration)
{
Url = configuration.ToString();
}
static void Main(string[] args)
{
CreateWebHostBuilder(args).Run();
}
public static IWebHost CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel((hostingContext, options) =>
{
var ipAddress = IPAddress.Parse(Url); // ERROR HERE
options.Listen(ipAddress, 9001);
}).Build();
I would have an error since the main
gets executed first then the CreateWebHostBuilder
so the Url
will not get filled in first. But if I use this code:
static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddSingleton(Configuration.GetSection("Url").Get<AppConfiguration>());
CreateWebHostBuilder(args).Run();
}
The Configuration.GetSection("Url")
is not recognized. How do I get the value from an appsettings.json in the Program.Main?
Update
as per "Tan" I made the necessary edits to my Program.cs
. I think I am near solving it. It's just that the "Url" is still null when it loads. Please see my edit:
static void Main(string[] args)
{
var builder = CreateWebHostBuilder(args);
builder.ConfigureLogging((context, builder) =>
{
Url = context.Configuration["ApplicationUrl"];
}).Build().Run();
}
public static IHostBuilder CreateWebHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseKestrel((hostingContext, options) =>
{
var ipAddress = IPAddress.Parse(Url);
options.Listen(ipAddress, 9001);
options.Limits.MaxRequestBodySize = null;
});
});
Please see the screenshot:
This is the appsettings.json
{
"AllowedHosts": "*",
"AcceptedOrigin": [ "http://localhost:4200" ],
"ApplicationUrl": "192.168.1.4"
}
Update 2
This is the appsettings.json
{
"AllowedHosts": "*",
"AcceptedOrigin": [ "http://localhost:4200" ],
"ApplicationUrl": "192.168.1.4"
}
static void Main(string[] args) {
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseKestrel((context, options) =>
{
options.Limits.MaxRequestBodySize = null;
// "192.168.1.4"
string url = context.Configuration["Url"];
var ipAddress = System.Net.IPAddress.Parse(url);
});
});
This is what I get in the Startup.cs
:
In the Program.cs
: