[原创]yii2搭建restful风格api接口强制返回json数据格式

yii2搭建了一个restful风格api接口,想要通过配置文件直接就强制所有action直接返回json数据格式,结果发现移动只要继承use yii\rest\ActiveController;控制器配置文件bootstrap和response的配置就会失效。最后看源码发现ActiveController继承\vendor\yiisoft\yii2\rest\Controller.php控制器里面通过behaviors行为重写了返回信息的数据格式。那么如果选择继承ActiveController控制器的话就只能在当前的行为重写返回数据格式规则,这样就需要每个控制器都去写规则了,如果想全局只能从配置文件里在response里执行到最后截取要出去数据根据自己的需求定义再输出,但是这样又不够灵活,自己看着办吧。参考如下配置内容根据自己需要修改:

return [
   'id' => 'app-api',
   'basePath' => dirname(__DIR__),
   'controllerNamespace' => 'api\controllers',
   'bootstrap' => [
      'log',
      [
         'class' => 'yii\filters\ContentNegotiator',
         'formats' => [
            'application/json' => yii\web\Response::FORMAT_JSON,
            //'text/html' => yii\web\Response::FORMAT_JSON,
            //'application/xml' => yii\web\Response::FORMAT_XML,
         ],
      ]
   ],
   'modules' => [
      'v1' => [  //module 与gii生成module配置的ModuleID 一致
         'class' => 'api\modules\v1\Module',
      ],
   ],
   'components' => [
      'request' => [
         'csrfParam' => '_csrf-api',
         'parsers' => [  //返回的数据格式为json
            'application/json' => 'yii\web\JsonParser',
            'text/json' => 'yii\web\JsonParser',
         ],
      ],
      //'response' => [
      // 'on beforeSend' => function($event) {
      //    if(is_array($event->sender->data)){
      //       $event->sender->format = 'json';
      //    }
      // },
      //],
      'response' => [
         'format' => 'json',//全局controller 返回json 不包括 ActiveController 会被行为重写
         //'charset' => 'UTF-8',
      ],
      'response' => [
         'format' => 'json',
         'formatters' => [
            \yii\web\Response::FORMAT_JSON => [
               'class' => 'yii\web\JsonResponseFormatter',
               'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
               'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
               // ...
            ],
         ],
      ],
      'response' => [
         'class' => 'yii\web\Response',
         'on beforeSend' => function ($event) {
            $response = $event->sender;
            $response->data = [
               'success' => $response->isSuccessful,
               'code' => $response->getStatusCode(),
               'message' => $response->statusText,
               'data' => $response->data,
            ];
            $response->statusCode = 200;
         },
      ],

在当前控制器里重写ActiveController控制器里的行为内容,参考着用。

class DefaultController extends ActiveController
{
   /**
    * Renders the test view for the module
    * @return string
    */
   //public function behaviors()
   //{
   // return [
   //    [
   //       'class' => 'yii\filters\ContentNegotiator',
   //       'only' => ['view', 'index'],  // in a controller
   //       // if in a module, use the following IDs for user actions
   //       // 'only' => ['user/view', 'user/index']
   //       'formats' => [
   //          'application/json' => Response::FORMAT_JSON,
   //       ],
   //       'languages' => [
   //          'en',
   //          'de',
   //       ],
   //    ],
   // ];
   //}
   public function behaviors()
   {
      $behaviors = parent::behaviors();
      $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
      //print_r($behaviors);exit;
      return $behaviors;
   }
此条目发表在服务器分类目录,贴了标签。将固定链接加入收藏夹。

发表评论