2014-12-22 17:30:11 4069次浏览 1条回答 0 悬赏 5 金钱

在进行RESTful时,默认输出格式是xml,我在web.php配置

'response' => ['format' => 'json',],
'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => ['player', 'custom']],
            ],
        ],
//    yii\web\Application类

public function handleRequest($request)
    {
        if (empty($this->catchAll)) {
            list ($route, $params) = $request->resolve();
        } else {
            $route = $this->catchAll[0];
            $params = array_splice($this->catchAll, 1);
        }
        try {
            Yii::trace("Route requested: '$route'", __METHOD__);
            $this->requestedRoute = $route;
            $result = $this->runAction($route, $params);
            if ($result instanceof Response) {
                return $result;
            } else {
                $response = $this->getResponse();
                //在这个地方打印$response,它的format属性还是默认值xml,没有改变?
                if ($result !== null) {
                    $response->data = $result;
                }

                return $response;
            }
        } catch (InvalidRouteException $e) {
            throw new NotFoundHttpException($e->getMessage(), $e->getCode(), $e);
        }
    }

为什么response对象的format属性还是xml

最佳答案

  • fly020212 发布于 2014-12-23 19:25 举报

    yii\rest\Controller 有定义了一个 behavior

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                    'application/xml' => Response::FORMAT_XML,
                ],
            ],
            'verbFilter' => [
                'class' => VerbFilter::className(),
                'actions' => $this->verbs(),
            ],
            'authenticator' => [
                'class' => CompositeAuth::className(),
            ],
            'rateLimiter' => [
                'class' => RateLimiter::className(),
            ],
        ];
    }
    

    contentNegotiator 这个 filter 会根据 客户端的 Accept 请求头, 重设 Responseformat 属性,yii\filters\ContentNegotiator

    简单说就是 如果 Accept: application/xml, 则 format 会被设置为 xml,如果是 Accept: application/json 会被设置为 json,你可以在 web.php 里面设置一个默认值,请求的时候会根据 Accept 请求头自动重设 format 属性,你的应用可以自适应 xml,或者 json,或者,把这个 filter 去掉,应用一直使用 json 格式

    你的问题可能就是,应用发送了 Accept: application/xml 请求头,发送 json 请求头就 ok 了

    没有找到数据。
您需要登录后才可以回答。登录 | 立即注册
jayce
主管

jayce

注册时间:2014-12-10
最后登录:2015-06-09
在线时长:48小时16分
  • 粉丝5
  • 金钱175
  • 威望0
  • 积分655

热门问题