【问题标题】:Hot Reload applying changes but not refreshing page in Visual Studio 2022在 Visual Studio 2022 中热重载应用更改但不刷新页面
【发布时间】:2022-01-04 02:59:53
【问题描述】:

我刚刚将一个 .NET 5 应用程序迁移到 .NET 6 并试图让热重载工作。

当我运行我的应用程序,更改一个值并点击热重载按钮(或使用保存时热重载选项)时,Visual Studio 通知我“代码更改已成功应用”:

尽管如此,这些更改并未反映在我的应用上。我已经使用 Full IIS、IIS Express 和 dotnet cli 运行了该应用程序,尽管它们之间没有区别。页面根本不会重新加载。

【问题讨论】:

    标签: .net-core .net-6.0 hot-reload visual-studio-2022


    【解决方案1】:

    我一直在努力解决这个问题,直到遇到an article by Scott Hanselman,它描述了使用限制性内容安全策略 (CSP) 可能会导致热重载问题。

    热重载在 .NET 6 中的工作方式是它在关闭 </body> 标记之前注入一个脚本(旁注:如果您没有正文标记,热重载也将不起作用)。此脚本设置与您的服务器的 websocket 连接,该连接侦听作为热重载过程的一部分所做的更改。如果您在 CSP 中指定的 ConnectSources 白名单不包含指向您的开发服务器的 websockets 地址,您将在控制台中收到类似以下错误:

    将预期的 ConnectSources 添加到您的 CSP 将解决控制台中的错误,并且热重载应该会再次开始工作。请注意,我正在使用流行的 NWebsec 包来设置我的 CSP。

        var customConnectSources = new List<string>
        {
            "https://*.signalr.net" // example
        };
    
        if (env.IsDevelopment())
        {
            // make exceptions to allow hot reload to work
            customConnectSources.Add("ws://localhost:*");
            customConnectSources.Add("wss://localhost:*");
        }
    
        app.UseCsp(options => options
            .DefaultSources(s => s
                .Self())
            .ConnectSources(s => s
                .Self()
                .CustomSources(customConnectSources.ToArray())));
    

    【讨论】:

      【解决方案2】:

      出于与 ajbeaven 的答案相同的原因,我还努力让 Hot Reload 正常工作('self' 不允许使用 ws)。将此添加到 index.cshtml 或 _Layout.cshtml 中的部分会有所帮助。此外,如果您碰巧在 IdentityServer 项目上工作,那么 CSP 会在 SecurityHeaderAttributes.cs 中设置,而 cshtml 文件中的值将被忽略。

      <meta http-equiv="Content-Security-Policy" content="connect-src ws://localhost:*;"> 
      

      【讨论】:

        猜你喜欢
        • 2022-01-02
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 2022-01-13
        • 2022-10-15
        • 2021-12-15
        • 2022-07-31
        • 2019-11-02
        相关资源
        最近更新 更多