Drupal 8:拦截404路由并将代码设置为200

时间:2017-12-11 16:22:06

标签: drupal-8

在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->setResponseCode(200)的内容,但我无法找到它。)

1 个答案:

答案 0 :(得分:0)

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

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

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

更改状态代码。

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

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

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