Auto refresh with dotnet watch for ASP .NET Core projects
Tags: csharp, blazor, aspnet, dotnet
Published: 2020-11-23 00:03:25

With the release of [.NET 5](https://docs.microsoft.com/en-us/dotnet/core/dotnet-five) came many performance improvements, [C# 9](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9) and [new features in ASP .NET Core](https://docs.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-5.0).

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](https://docs.microsoft.com/en-us/aspnet/core/tutorials/dotnet-watch?view=aspnetcore-5.0#run-net-core-cli-commands-using-dotnet-watch):

> **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:

```html
<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>
```

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](https://dev-to-uploads.s3.amazonaws.com/i/qpmk3ff3i03bu2iakid7.png)
**3)** Press **Ctrl + F5** (Start Without Debugging) **IMPORTANT: Only works if run without debbuging**

{% github https://github.com/dotnet/aspnetcore/issues/5456#issuecomment-726993425 %}

**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**

```json
{
  "iisSettings": {

    ...

  },
  "profiles": {

    ... ,

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

**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](https://github.com/dotnet/aspnetcore/issues/5456#issuecomment-666644982) (hopefully 🤞)

{% github https://github.com/dotnet/aspnetcore/issues/5456#issuecomment-666644982 %}