【问题标题】:dotnet core 3.1 web api - The name 'Configuration' does not exist in the current contextdotnet core 3.1 web api - 当前上下文中不存在名称“配置”
【发布时间】:2020-12-05 08:21:55
【问题描述】:

我正在使用 dotnet core 3.1 创建一个 Web API,但无法简单地获取配置设置。这是错误:

The name 'Configuration' does not exist in the current context

startup.cs 引用了配置:

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

我看过一些例子,他们似乎都利用了

var connectionString =  Configuration["ConnectionString"];

我在 appsettings.json 中看到了值,并且喜欢有一个 appsettings.Development.json 文件用于配置的事实。只是无法访问它们。

我确信这很简单,但由于某种原因,我花了很长时间才找到。如果 WeatherForecast 模板中包含对配置值的引用,那就太好了。

【问题讨论】:

    标签: asp.net-web-api .net-core


    【解决方案1】:
    var connectionString = Configuration.GetConnectionString("Default")
    

    确保你有ConnectionStrings 部分,有例子:

    "ConnectionStrings": {
      "Default": "Server=DESKTOP-L4QDV84;Database=Tournaments_MSA;Trusted_Connection=True;",
      "HangfireConnection": "Server=DESKTOP-L4QDV84;Database=HangfireDB;Trusted_Connection=True;"
    }
    

    编辑:

    IConfiguration 实例已存在于服务集合中,因此您可以通过在控制器构造函数中添加参数来轻松访问它。

    private readonly IConfiguration _configuration;
    public HomeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    

    然后您可以在控制器的方法中使用它

    【讨论】:

    • 但是在 Controller 类的 vscode 中,“配置”带有下划线,并给了我错误。我无法在控制器中引用配置。
    • 绝对。谢谢你。作为一个额外的问题,如果我在 appsettings.json 中添加一个不在“ConnectionStrings”下的部分,我如何从中获取信息?我不能使用 Configuration.GetConnectionString("xxxx"),那我该怎么称呼?
    • 我明白了。找到docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/…,看到我们可以这样称呼它 Configuration["section:key"]
    猜你喜欢
    • 2022-01-02
    • 2021-03-05
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多