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

Symfony框架路由导航时出现404 Not Found错误排查求助

Fixing Symfony 404 When Accessing /lucky/number

Let's break down the most likely causes and fixes for this 404 error— I've dealt with this exact scenario plenty of times when working with Symfony attribute routes.

First, the Critical Missing Piece in Your Controller

Looking at your LuckyController code, you're using the #[Route] attribute but haven't imported the required class! Symfony can't recognize the attribute without this use statement, so the route never gets registered.

Add this line at the top of your controller, right after the namespace:

use Symfony\Component\Routing\Annotation\Route;

Your corrected controller should look like this:

namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route; // <-- This was missing!

class LuckyController {
    #[Route('/lucky/number')]
    public function number(): Response {
        $number = random_int(0, 100);
        return $this->render('lucky/number.html.twig', [
            'number' => $number,
        ]);
    }
}

Next, Verify & Refresh

Once you've added the use statement, run these steps to confirm everything works:

  • Clear your Symfony cache (even in dev environment, cached routes can cause unexpected issues):

    php bin/console cache:clear
    
  • Check if the route is now registered using the debug command:

    php bin/console debug:router
    

    You should see /lucky/number listed in the output, mapped to App\Controller\LuckyController::number.

  • Try accessing the URL again— it should load the Twig template with your random lucky number.

Other Quick Checks (If the Above Doesn't Fix It)

  • Double-check your attributes.yaml route config: Your current setup is correct for loading attribute-based routes from the src/Controller directory, so this isn't the issue here.
  • Confirm your web server is pointing to the public/ directory of your Symfony project— if it's pointing to the root folder, routing won't work properly.
  • If you're using Symfony 4 or older, make sure the sensio/framework-extra-bundle is installed (though this isn't needed for Symfony 5+ with attribute routes).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:28:13