当前位置: 动力学知识库 > 问答 > 编程问答 >

rest - How to use behaviors when operating as RESTful?

问题描述:

I am following the instructions* on how to create a RESTful service with Yii2 but the behavior method causes the error:

Response content must not be an array.

If I remove the behavior method then I receive the JSON response that I expect. I tried removing the behavior method after reading another post**.

However I am a little unfamiliar with behaviors. Can we not use behaviors with Yii2 with REST or is this a bug? I would be very appreciate if someone could shed some light on this.

*http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html

**http://www.yiiframework.com/forum/index.php/topic/60432-rest-api-failing-with-behaviours/

网友答案:

Your problem is that you have overridden the behaviors() method completely. The parent classes have behaviors attached that negotiate the content headers and response format. To get round this your behaviors needs to return an array merged with the parent behaviors. So your behaviors() method will look like this;

public function behaviors() {
    return ArrayHelper::merge(parent::behaviors(), [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['post'],
                    ],
                ],
    ]);
}

You need to remember to add use yii\helpers\ArrayHelper at the top of the controller class.

分享给朋友:
您可能感兴趣的文章:
随机阅读: