前幾節開發Dapr應用程式時,我們使用 dapr cli 來啟動dapr服務,就像這樣:

dapr run --dapr-http-port 3501 --app-port 5001  --app-id frontend dotnet  .\FrontEnd\bin\Debug\net5.0\FrontEnd.dll

如果你想要通過dapr除錯服務呢?在這裡使用 dapr 執行時(daprd) 來幫助實現這一點。具體原理就是先從命令列中執行符合正確引數的 daprd,然後啟動您的程式碼並附加偵錯程式。

1.配置launch.json

vscode開啟專案,並建立launch.json

修改launch.json的preLaunchTask,自定義名字,preLaunchTask將引用在 tasks.json 檔案中定義的任務。

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Frontend-.NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
//"preLaunchTask": "build",
"preLaunchTask": "daprd-frontend",
"program": "${workspaceFolder}/FrontEnd/bin/Debug/net5.0/FrontEnd.dll",
"args": [],
"cwd": "${workspaceFolder}/FrontEnd",
"stopAtEntry": false,
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}

2.配置task.json

需要在task.json檔案中定義一個 daprd task和問題匹配器(problem matcher)。 這裡有兩個通過上述 preLaunchTask 成員引用。 在 dpred -frontend task下,還有一個dependsOn成員,它引用build任務,以確保最新的程式碼正在執行/除錯。 用了 problemMatcher,這樣當 daprd 程序啟動和執行時,VSCode 就能夠知道。

{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/FrontEnd/FrontEnd.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/FrontEnd/FrontEnd.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"${workspaceFolder}/FrontEnd/FrontEnd.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "daprd-frontend",
"command": "daprd",
"args": [
"-app-id",
"frontend",
"-app-port",
"5001",
"-dapr-http-port",
"3501",
"-placement-host-address",
"localhost:6050",
"-components-path",
"C:\\Users\\chesterychen\\.dapr\\components"
],
"isBackground": true,
"problemMatcher": {
"pattern": [
{
"regexp": ".",
"file": 1,
"location": 2,
"message": 3
}
],
"background": {
"beginsPattern": "^.*starting Dapr Runtime.*",
"endsPattern": "^.*waiting on port.*"
}
},
"dependsOn": "build"

},

]
}

因為沒有使用 dapr run* cli 命令, 所以執行 daprd list 命令將不會顯示當前正在執行的應用列表。

3.除錯

在StateController.GetAsync中新增斷點,執行並呼叫http://192.168.43.94:3501/v1.0/invoke/frontend/method/State。