tra*_*nte 8 php redirect cakephp http-status-code-404 cakephp-2.0
对于CakePHP错误,我知道存在CakeError和AppError解决方案.但我需要在控制器内进行重定向.
在AppController中存在:
function afterFilter() {
if ($this->response->statusCode() == '404')
{
$this->redirect(array(
'controller' => 'mycontroller',
'action' => 'error', 404),404
);
}
}
Run Code Online (Sandbox Code Playgroud)
但这不会创建404状态代码.它创建了一个302代码.我把代码更改为:
$this->redirect('/mycontroller/error/404', 404);
Run Code Online (Sandbox Code Playgroud)
但结果是一样的.
我添加了这个,它不起作用也弃用:
$this->header('http/1.0 404 not found');
Run Code Online (Sandbox Code Playgroud)
如何在控制器重定向中发送404代码?
swi*_*cki 19
如果要返回404错误,请使用内置的CakeError支持:
throw new NotFoundException();
Run Code Online (Sandbox Code Playgroud)
您可以从控制器中抛出此异常,它应该生成404响应.
还有更多的内置异常这里.
如果您有兴趣制作自定义错误页面,请参阅此帖子.
否则,我认为不可能返回404标头代码并仍然重定向.Http指定重定向状态代码在300s内,这是CakePHP遵循的约定.
出于某种原因,使用redirect()会将状态代码更改为3xx.如果要执行另一个操作并仍然返回404,则可以执行以下操作:
$this->controller->response->statusCode(404);
$this->controller->render('/mycontroller/error/404');
$this->controller->response->send();
Run Code Online (Sandbox Code Playgroud)
这将执行Mycontroller :: error(404)而不重定向.
| 归档时间: |
|
| 查看次数: |
20396 次 |
| 最近记录: |