1.ApiController.php

<?php

namespace app\controllers;

use yii\web\Response;

use yii\rest\ActiveController;

class ApiController extends ActiveController{

/**

* 将返回的数据设置成JSON格式

* {@inheritDoc}

* @see \yii\rest\Controller::behaviors()

*/

public function behaviors()

{

$behaviors=parent::behaviors();

$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;

return $behaviors;

}

/**

* 重置API基础内种的默认方法

* {@inheritDoc}

* @see \yii\rest\ActiveController::actions()

*/

public function actions(){

return [];

}

}

2.UserController.php

<?php

namespace app\controllers;

use yii;

use app\models\User;

use app\components\Utility;

class UserController extends ApiController{

/**

* 定义模型

*/

public $modelClass='app\models\User';


/**

* 过滤数据接收方式

* {@inheritDoc}

* @see \yii\rest\ActiveController::verbs()

*/

protected function verbs(){

return [

'login'=>['post'],

'checklogin'=>['get','post'],

];

}

/**

* 登录

*/

public function actionLogin(){

return ['ok'=>'login'];

}

/**

* 验证是否login

*/

public function actionChecklogin(){

Return [‘ok’=>’checklogin’];

}

}

3.Restful API测试工具PostMan的安装

现在chrome扩展只能从它的商店安装,但我发现这个商店被墙了,一直打不开。

方法:

⑴把附件的Postman_v3.0.17.crx修改后缀名成Postman_v3.0.17.rar

⑵解压缩rar,得到目录Postman_v3.0.17

⑶修改目录里的子目录_metadata成metadata

⑷Chrome中,打开扩展界面chrome://extensions/

(4.1)选中右上角的 [] 开发者模式

(4.2)加载正在开发的扩展程序

OK,成功。

4.在PostMan的URL里输入:

127.0.0.1/user/login或127.0.0.1/users/login,返回:'ok'=>'login'。因为在api_cfg.php里配置了:'POST users/login' => 'user/login',所以访问users/login会被重定向到user/login。