.NET核心控制器类。在声明中调用IConfiguration GetConnectionString会引发编译错误

时间:2018-12-14 11:11:46

标签: .net .net-core

为什么此代码给出错误?有什么解决方法吗?我需要在配置中使用连接字符串设置公共字符串ODataBaseAPIUrl变量,以便可以在控制器类的任何方法中使用它。

namespace AlioPosApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PosFunctionsController : ControllerBase
    {
        private readonly IConfiguration configuration;
        public PosFunctionsController(IConfiguration config)
        {
            this.configuration = config;

        }
//THIS NEXT LINE HAS A //COMPILE ERROR!!
//"cannot reference PosFunctionsController.configuration"
        public string ODataBaseAPIUrl = configuration.GetConnectionString("ODataBaseAPIUrl"); 
...

这是appsettings.json的内容:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "ODataBaseAPIUrl" : "http://localhost:7048/DynamicsNAV110/api/beta/companies(kj4081cc-de07-41f9-9f7a-6acdaf296fa4)/"
  },
  "AllowedHosts": "*"
}

2 个答案:

答案 0 :(得分:2)

按如下所示修复您的代码。

您不能那样做作业。您需要通过依赖注入将其放入构造器内

[Route("api/[controller]")]
[ApiController]
public class PosFunctionsController : ControllerBase
{
    private readonly IConfiguration configuration;
    private readonly string oDataBaseAPIUrl;
    public PosFunctionsController(IConfiguration config)
    {
        this.configuration = config;
        this.oDataBaseAPIUrl = configuration.GetConnectionString("ODataBaseAPIUrl");
    }

答案 1 :(得分:2)

字段在构造器运行之前被初始化,这就是为什么您不能使用configuration

的原因

您可以在构造函数中初始化值:

public PosFunctionsController(IConfiguration config)
{
    this.configuration = config;
    ODataBaseAPIUrl = configuration.GetConnectionString("ODataBaseAPIUrl");
}

或更改该字段,使其不被初始化,但会在每次调用时获取值:

public string ODataBaseAPIUrl => configuration.GetConnectionString("ODataBaseAPIUrl");