【问题标题】:Yii2 : Rest API return xml instead of jsonYii2:Rest API 返回 xml 而不是 json
【发布时间】:2021-03-22 08:42:25
【问题描述】:

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

所以 .. 我创建了一个 modules/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,
         ...
         ]

它给了我未找到 (#404)

【问题讨论】:

    标签: yii2 yii2-basic-app yii2-api


    【解决方案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键负责响应格式

    【讨论】:

    • 当我使用 'enableStrictParsing' =&gt; true, 我无法访问我的控制器操作时我需要知道一些事情它给了我找不到 404 我的错误是什么?
    【解决方案2】:

    你可以试试在控制器的action put中:

    \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',
         ];
     }
    

    【讨论】:

    • 我需要所有应用返回json,不单独
    • 不,它也不返回json
    猜你喜欢
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2016-02-11
    相关资源
    最近更新 更多