【发布时间】: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->setResponseCode(200) 这样的东西存在,但我找不到它。)
【问题讨论】:
标签: drupal-8