1

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:

enter image description here

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:

enter image description here

In the Program.cs:

enter image description here

1 Answer 1

2

In the file appsettings.json, you can define Url property like this:

{
  "Url": "https://example.com"
}

In the file Program.cs, inside Main method, you can access that property via ConfigureLogging extension method:

public class Program
{
    public static void Main(string[] args)
    {
        var builder = CreateHostBuilder(args);

        builder.ConfigureLogging((context, builder) => {
            // "https://example.com"
            string url = context.Configuration["Url"];

            // do stuff...
        }).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>()
            .UseKestrel(options =>
            {
                options.Limits.MaxRequestBodySize = null;
            });
        });
}

Update:

If you want to get the property value via UseKestrel extension method, you can assign it directly, no need to store in the field.

Because you will lose that value when the extension method finish (Url will become null outside the extension method)

public class Program
{
    public 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);
            });
        });
}

Screenshot:

1

Sign up to request clarification or add additional context in comments.

5 Comments

Sir, I made the necessary updates. I think it is almost there. But the problem is, the string Url still comes out null. Can you please help some more? Thank you. Please see my edit above.
@Ibanez1408 I've updated my answer. You can try again.
Sir, for some reason, "Url" property in the appsettings.json is not found. Did I create the appsettings.json correctly? Even on my Startup, I get null when I try to access it. Please see the update.
@Ibanez1408 That's because in your appsettings.json, you had replaced Url (in my example) with ApplicationUrl. Try again with context.Configuration["ApplicationUrl"];
I got it Sir. I just need to set my appsettings.json's property to "CopyToOutputDirectory" to "Copy if Newer". Thank you very very very VERY MUCH!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.