9

对于 CakePHP 错误,我知道存在 CakeError 和 AppError 解决方案。但我需要在控制器内进行重定向。

AppController中存在:

function afterFilter() {
    if ($this->response->statusCode() == '404')
    {
        $this->redirect(array(
            'controller' => 'mycontroller',
            'action' => 'error', 404),404
        );
    }
}

但这不会创建 404 状态代码。它创建一个 302 代码。我将代码更改为:

$this->redirect('/mycontroller/error/404', 404);

但结果是一样的。

我添加了这个,它没有工作也被弃用:

$this->header('http/1.0 404 not found');

如何在控制器重定向中发送 404 代码?

4

3 回答 3

22

如果要返回 404 错误,请使用内置的 CakeError 支持:

throw new NotFoundException();

您可以从控制器中抛出此异常,它应该会生成 404 响应。

这里有更多的内置异常。

如果您有兴趣制作自定义错误页面,请参阅这篇文章

否则,我认为不可能返回 404 标头代码并仍然重定向。Http 指定重定向状态代码为300s,这是 CakePHP 遵循的约定。

于 2012-06-29T21:13:16.700 回答
7

出于某种原因,使用 redirect() 会将状态码更改为 3xx。如果你想执行另一个动作并且仍然返回 404,你可以这样做:

$this->controller->response->statusCode(404);
$this->controller->render('/mycontroller/error/404');
$this->controller->response->send();

这将在没有重定向的情况下执行 Mycontroller::error(404)。

于 2013-01-02T19:42:59.293 回答
0

蛋糕PHP 3

use Cake\Network\Exception\NotFoundException;
...
throw new NotFoundException(__('Article not found'));
于 2017-04-02T13:14:41.137 回答