我正在尝试实现http://www.yiiframework.com/wiki/175/how-to-create-a-rest-api_sendResponse
并且在他们指定的功能上遇到了一些问题。下面是我的功能,但首先,让我解释一下问题。
我有一个abstract class BaseAPIController extends Controller
有这个_sendResponse
功能的。我有一个SomeObjectController extends BaseAPIController
. 在我的actionList
函数中,我有一行:
$this->_sendResponse(200, CJSON::encode($rows), 'application/json');
生成所需的输出。但是,状态码是 500!
即使我这样做:
$this->_sendResponse(200, ' ', 'application/json');
我仍然获得状态 500!
但是当我这样做时
$this->_sendResponse(200);
一切都很好,我得到了预期的空响应,状态码为 200。
这真让我抓狂!我需要做什么才能使其正常工作?
protected function _sendResponse($status = 200, $body = '', $content_type='text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
header($status_header);
header('Content-Type: ' . $content_type);
if ($body != '')
{
echo $body;
}
else
{
$message = '';
switch($status)
{
case 401:
$message = 'Not authorized.';
break;
case 404:
$message = 'Not found.';
break;
case 500:
$message = 'Internal server error.';
break;
case 501:
$message = 'Method not implemented.';
break;
default:
break;
}
$signature = ($_SERVER['SERVER_SIGNATURE'] == '') ?
$_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] :
$_SERVER['SERVER_SIGNATURE'];
// Needs to be completed with templates.
$body = '
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http="Content-Type" content="text/html"; charset=iso-8859-1">
<title>' . $status . ' ' . $this->_getStatusCodeMessage($status) . '</title>
</head>
<body>
<h1>' . $this->_getStatusCodeMessage($status) . '</h1>
<p>' . $message . '</p>
<hr />
</body>
</html>
';
echo $body;
}
Yii:app()->end();
}