Configuration.GetConnectionString returns null when running asp.net core on VS Code but fine on Visual Studio

bman picture bman · Sep 22, 2016 · Viewed 11.3k times · Source

Here is my appsettings.json file

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

This is how I retrieve the connection string:

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

My 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}"
        }
    ]
}

My tasks.json

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

Do you know how to fix this?

Answer

Sjoerd picture Sjoerd · Sep 22, 2016

You run the program from the root (solution level) and not from the project. Change your "cwd" in the launchsettings.json to ${workspaceRoot}\src\Chlx\