Symfony 3.4 NotFoundHttpException 找不到“GET /lucky/number”的路由

问题描述

我创建了一个 symfony 3.4 项目,并按照文档创建了一个控制器(我必须更改控制器命名空间)

<?PHP

namespace App\Controller;
//namespace AppBundle\Controller; this is the default namespace in the doc

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class LuckyController
{
    /**
     * @Route("/lucky/number")
     */
    public function numberAction()
    {
        $number = random_int(0,100);

        return new Response(
            '<html><body>Lucky number: '.$number.'</body></html>'
        );
    }
}

但是当我尝试访问 http://127.0.0.1:8000/lucky/number 时,我收到此错误

NotFoundHttpException  No route found for "GET /lucky/number"

我尝试清理缓存但没有用,我认为我不必下载任何 anootations 库,我不知道哪里出了问题

解决方法

如果您更改了命名空间,您还需要对配置进行一些更改。
您可以使用 controller.service_arguments:

标记单个控制器
# app/config/services.yml
services:
    # ...

    # explicitly configure the service
    App\Controller\LuckyController:
        tags: [controller.service_arguments]

或者,如果您已将整个 AppBundle 命名空间更改为 App 并且您正在使用 Symfony Standard Edition (version 3.4) services.yml 配置,只需将 AppBundle 的所有实例更改为 App :

# app/config/services.yml
services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    # makes classes in src/App available to be used as services
    App\:
        resource: '../../src/App/*'
        # you can exclude directories or files
        # but if a service is unused,it's removed anyway
        exclude: '../../src/App/{Entity,Repository}'

    # controllers are imported separately to make sure they're public
    # and have a tag that allows actions to type-hint services
    App\Controller\:
        resource: '../../src/App/Controller'
        public: true
        tags: ['controller.service_arguments']

当然,在进行任何更改后一定要清除缓存。