Quantcast
Channel: WCF, ASMX and other Web Services
Viewing all articles
Browse latest Browse all 555

Reading appsettings.json from controllers

$
0
0

I need to store some settings in appsettings.json. I've read and re-read several pages and I've got almost nowhere, other than confused. I've read the MS articles and I'm still having trouble. Here is an example appsettigns.json:

{"appSettings": {"UserId": "User1","UserPassword": "Password123","IVersion": "1.0","EPName": "TargetAPI","Hostname": "localhost","UserHTTPS": "N","LogFilePath": "./Logs/"
    }
}

Here is the Startup class:

    public class Startup
    {
        public IConfigurationRoot Configuration { get; set; }

        public void ConfigureServices(IServiceCollection services)
        {
            var mvcBuilder = services.AddMvc();
            mvcBuilder.AddXmlSerializerFormatters();

            services.AddOptions();

            services.Configure<IISOptions>(options =>
            {
                options.AutomaticAuthentication = false;
                options.ForwardClientCertificate = false;
            });

            services.Configure<ACLApplicationSettings>(Configuration.GetSection("ACLApplicationSettings");
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }            

            app.UseMvc();
            
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("No function called.");
            });
        }
    }

The controller has this at the top:

    [Route("api/[controller]")]
    [ApiController]
    public class CustomersController : ControllerBase
    {
        private readonly IOptions<ACLApplicationSettings> settings;

        public CustomersController(IOptions<ACLApplicationSettings> config)
        {
            settings = config;
        }

Now later in the class I would expect to be able to access the settings by typing:

settings.Value.ACLSettings.UserId

If I write the above line below the line in the constructor I can access the values. Outside of the constructor I cannot. What is going on? All I want to do is read settings that are held in an external file!


Viewing all articles
Browse latest Browse all 555

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>