使用檔案監看員開發 ASP.NET Core 應用程式Develop ASP.NET Core apps using a file watcher

作者:Rick AndersonVictor HurdugaciBy Rick Anderson and Victor Hurdugaci

dotnet watch 是一種工具,會在來源檔案變更時執行 .NET Core CLI 命令。dotnet watch is a tool that runs a .NET Core CLI command when source files change. 例如,檔案變更會觸發編譯、測試執行或部署。For example, a file change can trigger compilation, test execution, or deployment.

本教學課程使用現有的 Web API 與兩個端點:一個傳回加總,另一個傳回產品。This tutorial uses an existing web API with two endpoints: one that returns a sum and one that returns a product. 本教學課程已修正產品方法的 Bug。The product method has a bug, which is fixed in this tutorial.

下載範例應用程式Download the sample app. 這是由二個專案所組成:WebApp (ASP.NET Core Web API) 和 WebAppTests (Web API 的單元測試)。It consists of two projects: WebApp (an ASP.NET Core web API) and WebAppTests (unit tests for the web API).

在命令殼層中,巡覽至 WebApp 資料夾。In a command shell, navigate to the WebApp folder. 執行下列命令:Run the following command:

dotnet run

注意

您可以使用 dotnet run --project <PROJECT> 來指定要執行的專案。You can use dotnet run --project <PROJECT> to specify a project to run. 例如,從範例應用程式的根目錄執行 dotnet run --project WebApp 同時也會執行 WebApp 專案。For example, running dotnet run --project WebApp from the root of the sample app will also run the WebApp project.

主控台輸出會顯示類似如下的訊息 (指出應用程式正在執行,並等待要求):The console output shows messages similar to the following (indicating that the app is running and awaiting requests):

$ dotnet run
Hosting environment: Development
Content root path: C:/Docs/aspnetcore/tutorials/dotnet-watch/sample/WebApp
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

在網頁瀏覽器中,瀏覽至 http://localhost:<port number>/api/math/sum?a=4&b=5In a web browser, navigate to http://localhost:<port number>/api/math/sum?a=4&b=5. 您應該會看到 9 的結果。You should see the result of 9.

瀏覽至產品 API (http://localhost:<port number>/api/math/product?a=4&b=5)。Navigate to the product API (http://localhost:<port number>/api/math/product?a=4&b=5). 它會傳回 9,而非您預期的 20It returns 9, not 20 as you'd expect. 本教學課程稍後會修正該問題。That problem is fixed later in the tutorial.

dotnet watch 新增至專案Add dotnet watch to a project

dotnet watch 檔案監看員工具隨附於 .NET Core SDK 2.1.300 版本。The dotnet watch file watcher tool is included with version 2.1.300 of the .NET Core SDK. 使用舊版的 .NET Core SDK 需要以下的步驟。The following steps are required when using an earlier version of the .NET Core SDK.

  1. Microsoft.DotNet.Watcher.Tools 套件參考新增至 .csproj 檔案:Add a Microsoft.DotNet.Watcher.Tools package reference to the .csproj file:

    <ItemGroup>
        <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
    </ItemGroup>
    
  2. 執行下列命令來安裝 Microsoft.DotNet.Watcher.Tools 套件:Install the Microsoft.DotNet.Watcher.Tools package by running the following command:

    dotnet restore
    

使用 dotnet watch 執行 .NET Core CLI 命令Run .NET Core CLI commands using dotnet watch

任何 .NET Core CLI 命令都可以使用 dotnet watch 執行。Any .NET Core CLI command can be run with dotnet watch. 例如:For example:

命令Command 使用監看式的命令Command with watch
dotnet rundotnet run dotnet watch rundotnet watch run
dotnet run -f netcoreapp2.0dotnet run -f netcoreapp2.0 dotnet watch run -f netcoreapp2.0dotnet watch run -f netcoreapp2.0
dotnet run -f netcoreapp2.0 -- --arg1dotnet run -f netcoreapp2.0 -- --arg1 dotnet watch run -f netcoreapp2.0 -- --arg1dotnet watch run -f netcoreapp2.0 -- --arg1
dotnet testdotnet test dotnet watch testdotnet watch test

執行 WebApp 資料夾中的 dotnet watch runRun dotnet watch run in the WebApp folder. 主控台輸出指出 watch 已啟動。The console output indicates watch has started.

注意

您可以使用 dotnet watch --project <PROJECT> 來指定要監看的專案。You can use dotnet watch --project <PROJECT> to specify a project to watch. 例如,從範例應用程式的根目錄執行 dotnet watch --project WebApp run 同時也會執行並監看 WebApp 專案。For example, running dotnet watch --project WebApp run from the root of the sample app will also run and watch the WebApp project.

dotnet watch 進行變更Make changes with dotnet watch

請確認 dotnet watch 正在執行。Make sure dotnet watch is running.

修正 MathController.csProduct 方法的 Bug,使其傳回產品而非加總:Fix the bug in the Product method of MathController.cs so it returns the product and not the sum:

public static int Product(int a, int b)
{
    return a * b;
}

儲存檔案。Save the file. 主控台輸出指出 dotnet watch 已偵測到檔案變更,並重新啟動應用程式。The console output indicates that dotnet watch detected a file change and restarted the app.

驗證 http://localhost:<port number>/api/math/product?a=4&b=5 是否傳回正確的結果。Verify http://localhost:<port number>/api/math/product?a=4&b=5 returns the correct result.

使用 dotnet watch 執行測試Run tests using dotnet watch

  1. MathController.csProduct 方法變更回傳回加總。Change the Product method of MathController.cs back to returning the sum. 儲存檔案。Save the file.

  2. 在命令殼層中,瀏覽至 WebAppTests 資料夾。In a command shell, navigate to the WebAppTests folder.

  3. 執行 dotnet restoreRun dotnet restore.

  4. 執行 dotnet watch testRun dotnet watch test. 其輸出指出測試失敗,且監看員正在等候檔案變更:Its output indicates that a test failed and that the watcher is awaiting file changes:

    Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.
    Test Run Failed.
    
  5. 修正 Product 方法程式碼,使其傳回產品。Fix the Product method code so it returns the product. 儲存檔案。Save the file.

dotnet watch 會偵測檔案變更,並重新執行測試。dotnet watch detects the file change and reruns the tests. 主控台輸出指出測試成功。The console output indicates the tests passed.

自訂要監看的檔案清單Customize files list to watch

根據預設,dotnet-watch 會追蹤符合下列 Glob 模式的所有檔案:By default, dotnet-watch tracks all files matching the following glob patterns:

  • **/*.cs
  • *.csproj
  • **/*.resx

編輯 .csproj 檔案可將更多的項目新增至監看清單。More items can be added to the watch list by editing the .csproj file. 項目可以個別或使用 Glob 模式指定。Items can be specified individually or by using glob patterns.

<ItemGroup>
    <!-- extends watching group to include *.js files -->
    <Watch Include="**\*.js" Exclude="node_modules\**\*;**\*.js.map;obj\**\*;bin\**\*" />
</ItemGroup>

選擇不使用要監看的檔案Opt-out of files to be watched

dotnet-watch 可以設定成忽略其預設設定。dotnet-watch can be configured to ignore its default settings. 若要忽略特定的檔案,請將 Watch="false" 屬性新增至 .csproj 檔案的項目定義:To ignore specific files, add the Watch="false" attribute to an item's definition in the .csproj file:

<ItemGroup>
    <!-- exclude Generated.cs from dotnet-watch -->
    <Compile Include="Generated.cs" Watch="false" />

    <!-- exclude Strings.resx from dotnet-watch -->
    <EmbeddedResource Include="Strings.resx" Watch="false" />

    <!-- exclude changes in this referenced project -->
    <ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" Watch="false" />
</ItemGroup>

自訂監看式專案Custom watch projects

dotnet-watch 不限制為 C# 專案。dotnet-watch isn't restricted to C# projects. 您可以建立自訂的監看式專案來處理不同的案例。Custom watch projects can be created to handle different scenarios. 請考慮下列專案配置:Consider the following project layout:

  • test/test/
    • UnitTests/UnitTests.csprojUnitTests/UnitTests.csproj
    • IntegrationTests/IntegrationTests.csprojIntegrationTests/IntegrationTests.csproj

如果目標是監看這兩個專案,請建立設定成監看這兩個專案的自訂專案檔:If the goal is to watch both projects, create a custom project file configured to watch both projects:

<Project>
    <ItemGroup>
        <TestProjects Include="**\*.csproj" />
        <Watch Include="**\*.cs" />
    </ItemGroup>

    <Target Name="Test">
        <MSBuild Targets="VSTest" Projects="@(TestProjects)" />
    </Target>

    <Import Project="$(MSBuildExtensionsPath)\Microsoft.Common.targets" />
</Project>

若要開始監看兩個專案的檔案,請變更至 test 資料夾。To start file watching on both projects, change to the test folder. 執行下列命令:Execute the following command:

dotnet watch msbuild /t:Test

任一測試專案中的任何檔案發生變更時,就會執行 VSTest。VSTest executes when any file changes in either test project.

GitHub 中的 dotnet-watchdotnet-watch in GitHub

dotnet-watch 是 GitHub aspnet/AspNetCore 存放庫的一部分。dotnet-watch is part of the GitHub aspnet/AspNetCore repository.