Search code examples
c#.netasp.net-coremodel-view-controller

Passing IConfiguration to base controller


In this project I'm working on I have to create a controller using a base controller and the constructor of the base controller takes IConfiguration (I didn't create this base controller and have no control over the design). When I pass the IConfiguration parameter from the sub class constructor to the base class constructor, the base controller always complained about missing settings in the configuration although I've verified that they were there. The code looks like this:

    startup.cs:
    public class Startup {
    ......
       public IConfiguration Configuration { get; }
       public IWebHostEnvironment WebHostEnvironment { get; }

       public Startup(IConfiguration configuration, IWebHostEnvironment 
       webHostEnvironment) {
        Configuration = configuration;
        WebHostEnvironment = webHostEnvironment;
        }

       public void ConfigureServices(IServiceCollection services) {
       services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
       }

    ........
    }
    

  launchsettings.json:
  .....

  "profiles": {
"IIS Express": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "launchUrl": "api/v1/Test",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "local"
  }
},
.....

appsettings.local.json:
 ....
 "sec1": {
 "sec2": {
  "key": "local-keyyyyyyyy-hexadecimal",
  ......
        } 
}

...

public class TestController : myBaseController
{
  private readonly IConfiguration Configuration;
  public TestController(IConfiguration configuration,IOtherSerive iotherservice) : 
        base(configuration) {
       
        Configuration = configuration;
       ......
    }
  ......
 }

The base controller looks like this:

  .....
  public class myBaseController : ControllerBase 
 {
    
    private readonly IConfiguration configuration;
    public string key = string.Empty;

    public myBaseController(IConfiguration configuration) {
        key = configuration["sec1:sec2:key"];<----always complained about missing value from configuration here
       ........
    }
}

I wonder what's causing this problem?

p.s. The base controller is .net core 2.2 and the controller that inherited from the base controller is .net 3.1.


Solution

  • As I comment says, for this kind of issue, we could firstly check the appsetting.json is format is right or not and check you have used a special appsetting.json file setting in the program.cs.