如何在 Visual Studio 中使用 .NET 5(独立进程)调试 Azure Functions?

GLJ*_*GLJ 7 c# visual-studio .net-core azure-functions .net-5

我最近为 C# 中的 Azure Function 项目从 .NET Core 3.1 迁移到 .NET 5.0(使用隔离/进程外运行时)。一切都按预期工作。然而,每当我调试时,我的断点都没有命中。为什么我现在不能调试我的 Azure Function 应用程序,但我以前可以?

GLJ*_*GLJ 8

如果您使用的是 Visual Studio 版本 16.10 或更高版本,则在 Visual Studio 中进行调试非常简单。

微软的更新步骤如下

Visual Studio 与 Azure Functions 核心工具集成,以便你可以使用完整的 Azure Functions 运行时在本地测试你的函数。

  • 要运行您的函数,请在 Visual Studio 中按 F5。您可能需要启用防火墙例外,以便工具可以处理 HTTP 请求。在本地运行函数时,永远不会强制执行授权级别。

  • 从 Azure Functions 运行时输出中复制函数的 URL 并运行请求。当函数成功运行并将日志写入运行时输出时,将显示欢迎使用函数消息。

  • 若要停止调试,请在 Visual Studio 中按 Shift+F5。

验证该函数在本地计算机上正确运行后,就可以将项目发布到 Azure。


以下部分仅适用于使用 Visual Studio 16.9 或更早版本的情况。我强烈建议升级 Visual Studio 而不是使用这种“PITA”方法。

(请参阅 Andrii 的答案以获取替代解决方案)

在网上做了大量研究后,我了解到 .NET 5 用于 Azure Functions 的隔离进程默认不支持调试。要在 Visual Studio 中执行此操作,您需要执行以下步骤(链接曾经有效,但此后已更新)。

  1. 在 Visual Studio 中打开您的解决方案
  2. 在 Visual Studio 中打开 PowerShell(查看 -> 终端,或 Ctrl-`)
  3. 导航到您的项目 cd MyProject
  4. 在启用调试的情况下启动该功能func start –-dotnet-isolated-debug 此时,您应该会在终端输出中看到一个类似于以下内容的 PID
 Functions:
     HttpExample: [GET,POST] http://localhost:7071/api/HttpExample
 For detailed output, run func with --verbose flag.
 [2021-03-09T08:41:41.904Z] Azure Functions .NET Worker (PID: 81720) initialized in debug mode. Waiting for debugger to attach...
Run Code Online (Sandbox Code Playgroud)
  1. 打开Attach Process (Open -> Debug) 窗口,并选择在控制台输出中找到的PID 此时,断点现在有效并且将被命中。


And*_*rii 7

有一个简单的方法!

public static class Program
{
    public static void Main()
    {
        Debugger.Launch(); // The trick! <<=======================================

        using var host = new HostBuilder()
...
Run Code Online (Sandbox Code Playgroud)

然后像往常一样启动而不调试 (Ctrl+F5) 并附加相同的 Visual Studio 实例进行dotnet处理 附加调试器

瞧,您调试了您的功能!