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

如何在Visual Studio中使用DefaultAzureCredential运行Azure Function(托管身份)

本地用托管身份运行ServiceBusTrigger Azure Function的正确配置

一、修正local.settings.json配置

你的配置存在冗余项,托管身份模式下仅需保留必要配置:

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet",
        "ServiceBusConnString": "Endpoint=sb://sb-test-three.servicebus.windows.net/;Authentication=ManagedIdentity"
    }
}

说明:

  • 无需__serviceUri、__fullyQualifiedNamespace这类后缀配置,Azure Functions SDK会自动识别托管身份格式的连接字符串
  • 连接字符串支持两种格式:标准格式Endpoint=sb://<命名空间>.servicebus.windows.net/;Authentication=ManagedIdentity,或简化格式https://<命名空间>.servicebus.windows.net/ManagedIdentity

二、代码调整

你代码中手动创建的DefaultAzureCredential未实际使用,ServiceBusTrigger会自动调用DefaultAzureCredential获取身份令牌,可简化代码如下:

[FunctionName("Function1")]
public void Run([ServiceBusTrigger("topic-one", "sub-one", Connection = "ServiceBusConnString")]string mySbMsg, ILogger logger)
{
    logger.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
}

若需手动操作Service Bus客户端(比如主动发送消息),才需要显式使用DefaultAzureCredential,示例:

var credential = new DefaultAzureCredential();
var client = new ServiceBusClient("sb-test-three.servicebus.windows.net", credential);
var sender = client.CreateSender("topic-one");
// 后续消息发送逻辑

三、本地运行关键注意事项

  • 确保Visual Studio登录账户已在Service Bus命名空间级别分配Azure Service Bus Data Receiver(触发器接收权限)和Azure Service Bus Data Sender(若有发送操作)角色,角色分配通常需几分钟生效
  • 安装Azure Functions Core Tools版本需>=4.x,旧版本对托管身份本地支持不完善
  • 本地运行时,DefaultAzureCredential会自动优先使用Visual Studio登录身份,无需额外配置环境变量(除非指定其他身份源)

四、错误排查方向

若仍报错,检查以下内容:

  • 确认Service Bus主题、订阅名称拼写无误
  • 角色分配范围需覆盖Service Bus命名空间(或所属资源组),仅单个主题/订阅的权限不生效
  • 在Visual Studio中重新登录账户,确保身份上下文正确
  • 查看函数详细日志,区分是权限问题还是配置错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:30:53