在VS Code上运行asp.net核心时,Configuration.GetConnectionString返回null,但在Visual Studio上运行良好

时间:2016-09-22 00:23:22

标签: visual-studio-2015 asp.net-core connection-string visual-studio-code npgsql

这是我的 appsettings.json 文件

{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Port=5432;Database=db;User ID=postgres;Password=root"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

这是我检索连接字符串的方式:

// Only works when run through visual studio not on vs code
Configuration.GetConnectionString("DefaultConnection")

我的 launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceRoot}\\src\\Chlx\\bin\\Debug\\netcoreapp1.0\\Chlx.dll",
            "args": [],
            "cwd": "${workspaceRoot}",
            "stopAtEntry": false,
            "internalConsoleOptions": "openOnSessionStart",
            "launchBrowser": {
                "enabled": true,
                "args": "${auto-detect-url}",
                "windows": {
                    "command": "cmd.exe",
                    "args": "/C start ${auto-detect-url}"
                },
                "osx": {
                    "command": "open"
                },
                "linux": {
                    "command": "xdg-open"
                }
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceRoot}/Views"
            }
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach",
            "processId": "${command.pickProcess}"
        }
    ]
}

我的 tasks.json

{
    "version": "0.1.0",
    "command": "dotnet",
    "isShellCommand": true,
    "args": [],
    "tasks": [
        {
            "taskName": "build",
            "args": [
                "${workspaceRoot}\\src\\Chlx\\project.json"
            ],
            "isBuildCommand": true,
            "problemMatcher": "$msCompile"
        }
    ]
}

你知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

您从根(解决方案级别)而不是从项目运行程序。改变你的" cwd"在launchsettings.json中为$ {workspaceRoot} \ src \ Chlx \

答案 1 :(得分:0)

Configuration属性在Startup类中定义,并且通过依赖项注入进行初始化。这是使用dotnet new mvc -au Individual

创建的项目的示例。
  public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }