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

Bot Framework(FastAPI)本地模拟器正常,部署Azure Web App后仅接收GET请求

Azure Web App部署Python Echo Bot后仅接收GET请求的问题解决

问题背景

从微软GitHub仓库下载Python版Echo Bot示例,配置好Azure Bot的AppTenantId、AppId、AppPassword、SubscriptionId等参数后,本地Bot Emulator运行完全正常,可正确接收POST请求并返回回声响应。但部署到Azure Web App Service后出现异常:

部署步骤

  • 上传包含config.py、app.py及相关文件的project.zip包;
  • 验证/api/messages/端点可用且响应正常;
  • 通过Azure Bot的「Test in Local Web Chat」面板尝试与部署的服务通信;
  • 确认访问的端点为HTTPS,所有HTTP请求均已转发至HTTPS。

当前问题

部署后仅能接收到GET请求。无论是Azure Bot本地Web Chat面板的请求,还是浏览器直接访问端点,都只发送GET请求。通过打印请求对象的HEADER和METHOD属性,确认确实只收到GET请求,无法触发POST处理逻辑。


相关代码文件

app.py

# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import sys
import traceback
from datetime import datetime
from botbuilder.core import (
    TurnContext,
)
from botbuilder.integration.aiohttp import CloudAdapter, ConfigurationBotFrameworkAuthentication
from botbuilder.schema import Activity, ActivityTypes
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware

from bots import EchoBot
from config import DefaultConfig

CONFIG = DefaultConfig()

# Create adapter.
ADAPTER = CloudAdapter(ConfigurationBotFrameworkAuthentication(CONFIG))

# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
    print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
    traceback.print_exc()

    await context.send_activity("The bot encountered an error or bug.")
    await context.send_activity(
        "To continue to run this bot, please fix the bot source code."
    )
    if context.activity.channel_id == "emulator":
        trace_activity = Activity(
            label="TurnError",
            name="on_turn_error Trace",
            timestamp=datetime.utcnow(),
            type=ActivityTypes.trace,
            value=f"{error}",
            value_type="https://www.botframework.com/schemas/error",
        )
        await context.send_activity(trace_activity)


ADAPTER.on_turn_error = on_error

# Create the Bot
BOT = EchoBot()
APP = FastAPI()
APP.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

@APP.api_route("/api/messages", methods=["GET", "POST"])
async def messages(req: Request):
    print("METHOD:", req.method)
    print("HEADERS:", dict(req.headers))
    if req.method == "GET":
        return {"status": "ok"}  # Health check
    return await ADAPTER.process(req, BOT)

def init_func(*argv):
    return APP

if __name__ == "__main__":
    try:
        APP = init_func(None)
    except Exception as error:
        raise error

bots/echo.py

# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from botbuilder.core import ActivityHandler, MessageFactory, TurnContext
from botbuilder.schema import ChannelAccount


class EchoBot(ActivityHandler):
    async def on_members_added_activity(
        self, members_added: [ChannelAccount], turn_context: TurnContext
    ):
        for member in members_added:
            if member.id != turn_context.activity.recipient.id:
                await turn_context.send_activity("Hello! How can I help you?")

    async def on_message_activity(self, turn_context: TurnContext):
        return await turn_context.send_activity(
            MessageFactory.text(f"Echo: {turn_context.activity.text}")
        )

问题排查与解决方案

1. 修正Web App启动命令

Azure Web App运行FastAPI应用需指定正确的启动命令,否则会导致路由异常:

  • 进入Azure Portal的Web App资源 → 配置 → 常规设置 → 启动命令
  • 设置为:uvicorn app:APP --host 0.0.0.0 --port 8000
    (app:APP对应app.py中的FastAPI实例名称,端口8000为Azure Web App默认监听端口)

2. 检查Bot端点配置

  • 进入Azure Bot资源 → 设置 → 配置 → 消息端点
  • 确保地址为https://<你的Web App名称>.azurewebsites.net/api/messages,末尾不要加斜杠(带斜杠会触发301重定向,POST请求被转为GET)

3. 适配FastAPI与Bot Framework的集成

当前代码使用的CloudAdapter基于aiohttp,直接传递FastAPI的Request对象会导致兼容问题,需改用FastAPI专用集成:

  1. 在requirements.txt中添加依赖:botbuilder-integration-fastapi>=4.20.0
  2. 修改app.py中的导入和请求处理逻辑:
# 替换原有的aioadapter导入
from botbuilder.integration.fastapi import CloudAdapter, ConfigurationBotFrameworkAuthentication

# 保留ADAPTER初始化,请求处理逻辑不变
@APP.api_route("/api/messages", methods=["GET", "POST"])
async def messages(req: Request):
    print("METHOD:", req.method)
    print("HEADERS:", dict(req.headers))
    if req.method == "GET":
        return {"status": "ok"}
    return await ADAPTER.process(req, BOT)

4. 查看实时日志排查异常

  • 进入Azure Portal的Web App资源 → 日志 → 日志流
  • 查看实时日志,确认POST请求是否到达,是否有未捕获的异常导致请求失败,进而让Bot Framework转为发送GET请求做健康检查

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 22:00:11