DEV Community

Cover image for Auto refresh with dotnet watch for ASP .NET Core projects
Juan Cruz Fiant
Juan Cruz Fiant

Posted on

Auto refresh with dotnet watch for ASP .NET Core projects

With the release of .NET 5 came many performance improvements, C# 9 and new features in ASP .NET Core.

But today we are going to focus on a feature that was rarely discussed and that can save us a lot of time.

Auto refresh with dotnet watch

if you have installed the .NET 5 SDK or Visual Studio 16.8 (or later), running any ASP .NET Core project (regardless of the TargetFramework), the page will refresh every time it detects a change.

Extracted from MSDN documentation:

dotnet watch refreshes the browser when it detects changes to watched files. To do this, the watch command injects a middleware to the app that modifies HTML responses created by the app. The middleware adds a JavaScript script block to the page that allows dotnet watch to instruct the browser to refresh. Currently, changes to all watched files, including static content such as .html and .css files cause the app to be rebuilt.

The JavaScript script that is added is the following:



<script>
    setTimeout(function () {
        // dotnet-watch browser reload script
        let connection;
        try {
            connection = new WebSocket('ws://127.0.0.1:63435');
        } catch (ex) {
            console.debug(ex);
            return;
        }
        connection.onmessage = function (message) {
            if (message.data === 'Reload') {
                console.debug('Server is ready. Reloading...');
                location.reload();
            } else if (message.data === 'Wait') {
                console.debug('File changes detected. Waiting for application to rebuild.');
                const t = document.title; const r = ['', '', '']; let i = 0;
                setInterval(function () { document.title = r[i++ % r.length] + ' ' + t; }, 240);
            }
        }
        connection.onerror = function (event) { console.debug('dotnet-watch reload socket error.', event) }
        connection.onclose = function () { console.debug('dotnet-watch reload socket closed.') }
        connection.onopen = function () { console.debug('dotnet-watch reload socket connected.') }
    }, 500);
</script>


Enter fullscreen mode Exit fullscreen mode

Let me show you two ways to take advantage of this feature in Visual Studio

From ⚙ Options

1) Go to Tools > ⚙ Options > Projects and Solutions > ASP .NET Core
2) Select Auto build and refresh browser after saving changes in Auto build and refresh option options example
3) Press Ctrl + F5 (Start Without Debugging) IMPORTANT: Only works if run without debbuging

Comment for #5456

danroth27 avatar
danroth27 commented on

@porkopek Auto rebuild and auto refresh only work when you are not running with the debugger.

If you need debug your code:

4) Go to Debug > Attach to Process...
5) Select your application process (projectName.exe or iisexpress.exe)
6) Press Attach
7) If you make changes in your code, stop debbuging before (otherwise, the auto-refresh will not work)
8) Reattach to Process pressing Shift + Alt + P (Debug > Reattach to Process) to keep debugging.

From 🚀 launchSettings.json

1) add this in launchSettings.json



{
  "iisSettings": {

    ...

  },
  "profiles": {

    ... ,

    "Watch": {
      "commandName": "Executable",
      "executablePath": "dotnet.exe",
      "workingDirectory": "$(ProjectDir)",
      "commandLineArgs": "watch run",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}


Enter fullscreen mode Exit fullscreen mode

2) Change debug profile to Watch
3) Press Ctrl + F5 (Start Without Debugging)

If you need debug your code:

4) Go to Debug > Attach to Process...
5) Select your application process (projectName.exe)
6) Press Attach
7) If you make changes in your code, you need to Reattach to Process pressing Shift + Alt + P (Debug > Reattach to Process)

Wrapping Up

This is a great help that saves a lot of time for those of us developing with Blazor, while we wait for the release of Hot Reload in .NET 6 (hopefully 🤞)

Comment for #5456

danroth27 avatar
danroth27 commented on

@qin-guan Hot reload is not planned for .NET 5 due to the limited time left in that release. We're hoping to deliver hot reload for .NET 6.

Top comments (1)

Collapse
 
zabronm profile image
zabronm

Thank you for the article.

However, I did not get the intention of "Step 4: If you need to debug"; Are you saying if to debug your project, you need to reverse what has been done from Step 1 of what? Also, whats is the purpose of the adding the script in launchSettings.JSon file; and how does it relate to the "dotnet watch run"

Thanks again