By using IConfiguration, you can access appsetting.json content in asp.net core. Using it in Startup is straightforward:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //using Configuration app.ConfigureExceptionHandler(Configuration["Logs:Url"], Configuration["Logs:ExceptionIndex"]); } }
And in Controller level is similar by taking credit of HttpContext:
public class Controller : controllerBase { protected IActionResult Sample() { var services = HttpContext.RequestServices; var configuration = (IConfiguration)services.GetService(typeof(IConfiguration)); var url = configuration["FtpInformation:FtpRead"]; return ok(); } }
But if you want to use it in a class rather than Asp.net level. In a class library you can use the following code snippet:
public class CacheService : ICacheService { private static IConfiguration configuration; private static string Address { get { return configuration["CacheServer:Url"]; } } public CacheService() { var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); configuration = builder.Build(); } public async Task<object> GetAsync(object key) { //use address in the method } }
Cheers!