ファイル ウォッチャーを使用した ASP.NET Core アプリの開発Develop ASP.NET Core apps using a file watcher
作成者: Rick Anderson と Victor 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.
このチュートリアルでは、エンドポイントが 2 つの既存の Web API を利用します。合計を返すエンドポイントと積を返すエンドポイントです。This tutorial uses an existing web API with two endpoints: one that returns a sum and one that returns a product. 積のメソッドにはバグがあり、このチュートリアルで修正します。The product method has a bug, which is fixed in this tutorial.
サンプル アプリをダウンロードしてください。Download the sample app. これには次の 2 つのプロジェクトが含まれています。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.
Web ブラウザーで、http://localhost:<port number>/api/math/sum?a=4&b=5
に移動します。In 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
). 予想していた 20
ではなく、9
が返されます。It 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.
Microsoft.DotNet.Watcher.Tools
パッケージ参照を .csproj ファイルに追加します。Add aMicrosoft.DotNet.Watcher.Tools
package reference to the .csproj file:<ItemGroup> <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" /> </ItemGroup>
次のコマンドを実行して
Microsoft.DotNet.Watcher.Tools
パッケージをインストールします。Install theMicrosoft.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 | コマンドと watchCommand with watch |
---|---|
dotnet rundotnet run | dotnet watch rundotnet watch run |
dotnet run -f netcoreapp3.1dotnet run -f netcoreapp3.1 | dotnet watch run -f netcoreapp3.1dotnet watch run -f netcoreapp3.1 |
dotnet run -f netcoreapp3.1 -- --arg1dotnet run -f netcoreapp3.1 -- --arg1 | dotnet watch run -f netcoreapp3.1 -- --arg1dotnet watch run -f netcoreapp3.1 -- --arg1 |
dotnet testdotnet test | dotnet watch testdotnet watch test |
WebApp フォルダーの dotnet watch run
を実行します。Run dotnet watch run
in the WebApp folder. コンソール出力に、watch
が起動したことが示されます。The console output indicates watch
has started.
Web アプリで dotnet watch run
を実行すると、準備完了後にブラウザーが起動して、そのアプリの URL に移動します。Running dotnet watch run
on a web app launches a browser that navigates to the app's URL once ready. dotnet watch
は、これを実行するために、アプリのコンソール出力を読み取り、WebHost によって表示される準備完了メッセージを待機します。dotnet watch
does this by reading the app's console output and waiting for the the ready message displayed by WebHost.
dotnet watch
によってウォッチ対象のファイルに対する変更が検出されると、ブラウザーが最新の情報に更新されます。dotnet watch
refreshes the browser when it detects changes to watched files. これを行うために、アプリによって作成された HTML 応答を変更するミドルウェアが、watch コマンドによってアプリに挿入されます。To do this, the watch command injects a middleware to the app that modifies HTML responses created by the app. このミドルウェアでは、dotnet watch
がブラウザーに更新を指示する JavaScript スクリプト ブロックがページに追加されます。The middleware adds a JavaScript script block to the page that allows dotnet watch
to instruct the browser to refresh. 現在、ウォッチ対象のすべてのファイルに対する変更 ( .html ファイル、 .css ファイルなどの静的コンテンツ) によって、アプリが再ビルドされます。Currently, changes to all watched files, including static content such as .html and .css files cause the app to be rebuilt.
dotnet watch
:dotnet watch
:
- 既定では、ビルドに影響するファイルのみをウォッチします。Only watches files that impact builds by default.
- 追加でウォッチ対象となるファイル (構成により) でも、ビルドが行われます。Any additionally watched files (via configuration) still results in a build taking place.
構成の詳細については、このドキュメントの「dotnet-watch の構成」を参照してください。For more information on configuration, see dotnet-watch configuration in this document
注意
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.cs の Product
メソッドのバグを修正して、合計ではなく積を返すようにします。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
MathController.cs の
Product
メソッドを元に戻して合計を返すようにします。Change theProduct
method of MathController.cs back to returning the sum. ファイルを保存します。Save the file.コマンド シェルで、WebAppTests フォルダーに移動します。In a command shell, navigate to the WebAppTests folder.
dotnet restore を実行します。Run dotnet restore.
dotnet watch test
を実行します。Rundotnet 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.
積を返すように
Product
メソッドのコードを修正します。Fix theProduct
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. 特定のファイルを無視するには、 .csproj ファイルで項目の定義に Watch="false"
属性を追加します。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.
dotnet-watch の構成dotnet-watch configuration
一部の構成オプションは、環境変数を通じて dotnet watch
に渡すことができます。Some configuration options can be passed to dotnet watch
through environment variables. 使用できる変数は、次のとおりです。The available variables are:
設定Setting | 説明Description |
---|---|
DOTNET_USE_POLLING_FILE_WATCHER |
"1" または "true" に設定した場合、dotnet watch によって、CoreFx の FileSystemWatcher ではなく、ポーリング ファイル ウォッチャーが使用されます。If set to "1" or "true", dotnet watch uses a polling file watcher instead of CoreFx's FileSystemWatcher . ネットワーク共有または Docker でマウントされたボリューム上のファイルをウォッチするときに使用します。Used when watching files on network shares or Docker mounted volumes. |
DOTNET_WATCH_SUPPRESS_MSBUILD_INCREMENTALISM |
既定では、復元の実行や、ファイルが変更されるたびにウォッチ対象のファイルのセットの再評価が行われるなどの特定の操作が実行されないようにすることで、dotnet watch によってビルドが最適化されます。By default, dotnet watch optimizes the build by avoiding certain operations such as running restore or re-evaluating the set of watched files on every file change. "1" または "true" に設定した場合、これらの最適化は無効になります。If set to "1" or "true", these optimizations are disabled. |
DOTNET_WATCH_SUPPRESS_LAUNCH_BROWSER |
dotnet watch run は、launchSettings.json で構成された launchBrowser を使用して、Web アプリ用のブラウザーの起動を試みます。dotnet watch run attempts to launch browsers for web apps with launchBrowser configured in launchSettings.json. "1" または "true" に設定した場合、この動作は抑制されます。If set to "1" or "true", this behavior is suppressed. |
DOTNET_WATCH_SUPPRESS_BROWSER_REFRESH |
dotnet watch run は、ファイルの変更を検出すると、ブラウザーを最新の情報に更新することを試みます。dotnet watch run attempts to refresh browsers when it detects file changes. "1" または "true" に設定した場合、この動作は抑制されます。If set to "1" or "true", this behavior is suppressed. DOTNET_WATCH_SUPPRESS_LAUNCH_BROWSER が設定されている場合も、この動作は抑制されます。This behavior is also suppressed if DOTNET_WATCH_SUPPRESS_LAUNCH_BROWSER is set. |
GitHub での dotnet-watch
dotnet-watch
in GitHub
dotnet-watch
は GitHub の aspnet/AspNetCore リポジトリに含まれています。dotnet-watch
is part of the GitHub dotnet/AspNetCore repository.