【问题标题】:Passing IConfiguration to base controller将 IConfiguration 传递给基本控制器
【发布时间】:2020-10-06 17:09:29
【问题描述】:

在我正在进行的这个项目中,我必须使用基本控制器创建一个控制器,并且基本控制器的构造函数采用 IConfiguration(我没有创建这个基本控制器并且无法控制设计)。当我将 IConfiguration 参数从子类构造函数传递给基类构造函数时,基控制器总是抱怨配置中缺少设置,尽管我已经验证它们在那里。代码如下所示:

    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;
       ......
    }
  ......
 }

基本控制器如下所示:

  .....
  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
       ........
    }
}

我想知道是什么导致了这个问题?提前致谢!

附言基本控制器是 .net core 2.2,从基本控制器继承的控制器是 .net 3.1。

【问题讨论】:

  • 根据你的描述和代码,我自己做了一个测试demo,效果很好。我可以从 appsetting.json 文件中获取配置。 Result Image。您能否发布 appsetting.json 或 appsetting.development.json 和 program.cs 代码的所有设置?我猜你可能在 appsetting.json 中使用了错误的格式,或者在 program.cs 中使用了特殊的 appsetting.json 文件设置。
  • 我使用的是相同的概念,它在我的项目中运行良好,基于 3.1。看起来您在 appSettings.json 中有问题。
  • 谢谢大家!原来是 appsettings json 中的一个拼写错误的设置。

标签: .net api asp.net-core model-view-controller


【解决方案1】:

正如我评论所说,对于此类问题,我们可以首先检查 appsetting.json 格式是否正确,并检查您是否在 program.cs 中使用了特殊的 appsetting.json 文件设置。

【讨论】:

    猜你喜欢
    • 2013-04-08
    • 2020-06-30
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2016-06-02
    相关资源
    最近更新 更多