在 src/Controller 中创建控制器,用 PHP 属性定义 GET 路由。方法返回 Response 或 JsonResponse,而不是随意输出并提前退出;这样框架事件、错误处理与响应头才能正常参与请求。
操作示例
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
class HealthController extends AbstractController
{
#[Route('/health', name: 'health', methods: ['GET'])]
public function index(): JsonResponse
{
return $this->json(['ok' => true]);
}
}检查结果与使用要点
执行 php bin/console debug:router 查看 health 路由。访问 /health 应得到 JSON,若没有注册,检查控制器命名空间与路由资源配置。路由参数需要 requirements 等限制时,应在映射层写清楚,再进行业务验证。