Symfony框架路由导航时出现404 Not Found错误排查求助
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:clearCheck if the route is now registered using the debug command:
php bin/console debug:routerYou should see
/lucky/numberlisted in the output, mapped toApp\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.yamlroute config: Your current setup is correct for loading attribute-based routes from thesrc/Controllerdirectory, 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-bundleis installed (though this isn't needed for Symfony 5+ with attribute routes).
内容的提问来源于stack exchange,提问作者Bernardo selo

