You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移到.NET 5后带有ServiceBusTrigger的Azure Function未被识别问题咨询

问题排查与解决方案

1. 修正Program.cs配置加载与服务注册

你自行构建的Configuration实例未绑定到HostBuilder,导致宿主无法读取appsettings.json中的配置,同时缺失ServiceBus扩展的注册步骤,修正后代码如下:

public class Program
{
    public static Task Main(string[] args)
    {
        var host = new HostBuilder()
            .ConfigureFunctionsWorkerDefaults()
            .ConfigureAppConfiguration((context, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddEnvironmentVariables();
            })
            .ConfigureServices((context, services) =>
            {
                // 注册ServiceBus扩展
                services.AddServiceBus();
                services.AddTransient<IService1, Service1>();
            })
            .Build();
        
        return host.RunAsync();
    }
}

2. 修正配置文件与复制规则

2.1 新增appsettings.json输出配置

你的项目文件中仅配置了local.settings.json的复制规则,appsettings.json不会被复制到运行目录,需要在项目文件的ItemGroup中新增如下配置:

<None Update="appsettings.json">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

2.2 修正连接串配置路径

.NET Isolated模式下的触发器默认优先从Values节点读取配置,你可以选择两种方案:

  • 方案1:将ServiceBus连接串添加到local.settings.json的Values节点(本地运行生效):
{
  "IsEncrypted": false,
  "AzureWebJobsStorage": "UseDevelopmentStorage=true",
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "ServiceBusConnectionString": "Endpoint=sb://****.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=******"
  }
}
  • 方案2:保持appsettings.json的ConnectionStrings配置不变,在触发器的Connection属性中指定配置路径前缀:Connection = "ConnectionStrings:ServiceBusConnectionString"

3. 修正函数绑定参数类型与属性

.NET 5 Isolated模式下的ServiceBusTrigger不支持旧版Microsoft.Azure.ServiceBus.Message类型,需要替换为Azure.Messaging.ServiceBus.ServiceBusReceivedMessage,同时确认特性使用正确:

public class MyFunction
{
    private readonly IService1 service;

    public MyFunction(IService1 service)
    {
        this.service = service;
    }

    [Function("Function1")] // 1.5.1版本Worker SDK兼容[FunctionName],建议统一用[Function]
    public async Task ProcessMessage([ServiceBusTrigger("topic", "subscription", Connection = "ServiceBusConnectionString")] ServiceBusReceivedMessage message)
    {
        await service.Process(message);
    }
}

4. 可选:升级兼容Nuget包版本

你当前使用的Worker SDK版本较低,可升级到.NET 5支持的最新稳定版本减少兼容问题:

<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.10.1" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.ServiceBus" Version="5.13.1" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.7.0" OutputItemType="Analyzer" />

内容的提问来源于stack exchange,提问作者zameb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:15:03