0

我刚刚使用 Yii2 构建了一个应用程序作为 Flutter App 的后端

所以..我创建了一个模块/api文件夹,并在其中创建了控制器,就像这样

<?php

 namespace app\modules\api\controllers;

 use yii\web\Controller;
 use yii\rest\ActiveController;


 class AdController extends ActiveController
 {
   public  $modelClass = 'app\models\Ad';
 }

它工作正常,但它返回 XML

我在 web.php 中尝试过

'components' => [
    'response' => [
        'format' => \yii\web\Response::FORMAT_JSON,
    ],
 ],

'request' => [
        'parsers' => [
            'application/json' => 'yii\web\JsonParser',
        ]
    ],

但它仍然返回 XML

更新

当我使用

        'urlManager' => [ 
        ....
        'enableStrictParsing' => true,
         ...
         ]

它给了我Not Found (#404)

4

2 回答 2

1

首先创建一个基本控制器

并使用此配置覆盖行为方法

namespace micro\controllers;
class ActiveController extends yii\rest\ActiveController {

    public function behaviors() {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator'] = [
            'class' => 'yii\filters\ContentNegotiator',
            'formats' => [
                'application/json' => \yii\web\Response::FORMAT_JSON,
            ]
        ];
        return $behaviors;
    }
}

而不是在所有项目控制器中扩展它

contentNegotiator键负责响应格式

于 2021-03-22T13:24:02.997 回答
0

您可以尝试在控制器操作中放置:

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON

例如:

public function actionAd()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    // return response
}

但是,您应该为serialize

 class AdController extends ActiveController
 {
     public $modelClass = 'app\models\Ad';
     public $serializer = [
         'class' => 'yii\rest\Serializer',
         'collectionEnvelope' => 'items',
     ];
 }
于 2021-03-22T08:48:45.903 回答