lengyunfei0 2016-01-14 09:37:11 10869次浏览 1条评论 0 0 0

修改:vender/yiisoft/yii2/rest/ActiveController.php 文件
引入类:use yii\web\Response;
增加属性:protected $formatType = 'json';
重写方法:

public function behaviors()
{
	$behaviors = parent::behaviors();
	switch($this->formatType)
	{
		default :
		case 'json' :
		case 'jsonp' :
			$formatType = Response::FORMAT_JSON;
			$behaviors['contentNegotiator']['formats'] = [];
			$behaviors['contentNegotiator']['formats']['application/json'] = $formatType;
			break;
		case 'xml' :
			$formatType = Response::FORMAT_XML;
			$behaviors['contentNegotiator']['formats'] = [];
			$behaviors['contentNegotiator']['formats']['application/xml'] = $formatType;
			break;            
		case 'html' :
			$formatType = Response::FORMAT_HTML;
			$behaviors['contentNegotiator']['formats'] = [];
			$behaviors['contentNegotiator']['formats']['html/text'] = $formatType;
			break;
	}
	return $behaviors;
}
  • 评论于 2016-01-14 10:11 举报

    不建议直接修改框架代码,如果以后有升级这些改动非常容易被覆盖掉.
    还是自己写基类比较好

    1 条回复
    评论于 2016-01-14 14:54 回复

    嗯,也可以写基类。不过原理都是这样。

您需要登录后才可以评论。登录 | 立即注册