【问题标题】:Symfony 3.4 NotFoundHttpException No route found for "GET /lucky/number"Symfony 3.4 NotFoundHttpException 找不到“GET /lucky/number”的路由
【发布时间】:2021-09-17 08:54:52
【问题描述】:

我创建了一个 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 库,我不知道出了什么问题

【问题讨论】:

  • 那么你为什么不认为你需要一个注解包呢? symfony.com/doc/current/page_creation.html#annotation-routes
  • 您尝试过什么解决问题的方法?你被困在哪里了?
  • @Cerad 3.4 doc页面并没有说要安装包,不是有一段时间默认包含了吗?
  • @ArleighHix 试图让幸运数字控制器工作的人往往是新开发人员。很难说他们是如何开始他们的项目的,尤其是当他们仍在使用一个古老的不受支持的版本时。有许多相同的问题有许多非常奇怪的解决方案。在一种情况下,开发人员忘记了开始

标签: symfony symfony-3.4


【解决方案1】:

如果您更改了命名空间,您还需要对配置进行一些更改。
您可以使用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']

当然,在进行任何更改后总是清除缓存。

【讨论】:

  • 错误信息表示路由不存在。生成路由独立于控制器服务。他们最终可能需要也可能不需要使用您发布的代码,但他们需要先定义路线。
猜你喜欢
  • 2018-05-30
  • 2015-11-02
  • 2016-03-27
  • 1970-01-01
  • 2017-01-01
  • 2019-02-22
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
相关资源
最近更新 更多