【问题标题】:How to create 2 actions with same path but different http methods Symfony2如何创建 2 个具有相同路径但不同 http 方法的操作 Symfony2
【发布时间】:2015-04-04 07:02:25
【问题描述】:

我使用 symfony 路由注释,我已经将 http_method_override 设置为 true

我想根据 http 方法创建两个不同的操作,但具有不同的行为,如下所示:

/**
 * Event controller.
 *
 * @Route("/event")
 */
class EventController extends Controller
{

    /**
     * Lists all Event entities.
     *
     * @Route("/", name="event")
     * @Method("GET")
     * @Template() // default template (index.html.twig)
     */
    public function indexAction()
    {
       ...
    }

    /**
     * Creates a new Event entity.
     *
     * @Route("/", name="event_create")
     * @Method("POST")
     * @Template("...") // a special template new.html.twig
     */
    public function createAction(Request $request)
    {
        ...
    }

但是当我尝试访问/event/时,有一个405页面说:

找不到“GET /event/”的路由:不允许的方法(允许:POST)

当我尝试使用php app/console router:debug 列出我的路线时:

  event_create             POST   ANY    ANY  /event/                                      
  event                    GET    ANY    ANY  /event/week/{timestamp}                      
  event_new                GET    ANY    ANY  /event/new
  event_show               GET    ANY    ANY  /event/{id}                                  
  event_edit               GET    ANY    ANY  /event/{id}/edit
  event_update             PUT    ANY    ANY  /event/{id}
  event_delete             DELETE ANY    ANY  /event/{id} 

【问题讨论】:

  • 你也可以只创建一个路由,然后像这样@Method({"GET", "POST"}) 把两个方法加在一起
  • 感谢您的快速回答 gp_sflover 但我需要获得两种不同的行为(列出和创建),因此需要两种不同的方法。但我找到了我愚蠢的答案^^

标签: php symfony routing http-method


【解决方案1】:

很抱歉,我刚刚意识到阅读我的问题 下面的另一种方法 路径 /event/week/{timestamp} 也被命名为“事件”强> :/

所以我将此方法重命名为 event_week 并且它有效。

【讨论】:

  • 难以置信,我遇到了同样的问题!使用相同的解决方案......这是一个比我更常见的问题
猜你喜欢
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
相关资源
最近更新 更多