This tends to happen particularly with vscode as I'd assume because of how one configures the launch.json
.
Based on this answer I had to reconfigure the base path the configuration is being searched for to that of DLL's path, and since the default setting was optional it was hard to track this down on a .net core 3.1 & net 5.0 app. Here's how I've reconfigured
Program.cs
:
using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace API
{
public class Program
{
public static int Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
return 0;
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(c =>
{
var codeBase = Assembly.GetExecutingAssembly().Location;
var uri = new UriBuilder(codeBase);
var path = Uri.UnescapeDataString(uri.Path);
var assembyDirectory = Path.GetDirectoryName(path);
c.SetBasePath(assembyDirectory);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
;
}
}
}
I could access the configuration fine in Startup.cs
:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Model;
namespace API
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var myOptions = Configuration.To<ApiConfig>();
services.AddAuthentication(myOptions.Secret);
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}