【问题标题】:Drupal 8: Intercepting a 404 route and setting to code to 200Drupal 8:拦截 404 路由并将代码设置为 200
【发布时间】:2017-12-11 16:22:06
【问题描述】:

在 Drupal 8 站点中,/some/random/path 将返回“404 not found”。在运行时,我需要拦截其中一些路径并将它们设置为返回有效的东西。

我添加了一个名为MYMODULE.services.yml的文件:

services:
  mymodule.route_subscriber:
    class: Drupal\MYMODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

然后,在 ./src/Routing/RouteSubscriber.php 中,我有:

<?php
namespace Drupal\MYMODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.404')) {
      $route->setDefault('_controller', '\Drupal\MYMODULE\Controller\MyController::load');
    }
  }
}

然后在 ./src/Controller/SpokeController.php 中,我有:

class SpokeController extends ControllerBase {

  public function load() {
    $path = \Drupal::service('path.current')->getPath();

    if (path_is_valid()) { // I can only do this at runtime.
      // Is there a way to add something here like:
      // $this->setResponseCode(200);
      // return a render array for the content.
    }
    else {
      // return a render array like "page not found".
    }
  }

}

在我的控制器中,我可以将响应代码从 404 更改为 200 吗? (我期待像$this-&gt;setResponseCode(200) 这样的东西存在,但我找不到它。)

【问题讨论】:

    标签: drupal-8


    【解决方案1】:

    This change record 解释了如何实现这一点:

    在 SpokeController::load() 中,我们可以返回一个包含以下内容的渲染数组:

    $render['#attached']['http_header'][] = ['Status', "200"];
    

    这会改变状态码。

    要动态更改标题,可以在 alterRoutes() 中添加以下行:

    $route->setDefault('_title_callback', '\Drupal\steward_spoke\Controller\SpokeController::title');
    

    然后,在 SpokeController::title() 中返回一个标题。所有这一切让您可以动态地返回路线的标题、内容和状态代码。

    【讨论】:

      猜你喜欢
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多