如何在 Yii2 api 模块上设置 HTTP 标头过期?

问题描述 投票:0回答:2

我正在我的班级上初始化我的 Api 模块

init()
用这个

public function init()
{
    //parent::init();
    Yii::$app->request->parsers = ['application/json' => 'yii\web\JsonParser'];
    Yii::$app->request->enableCsrfValidation = false;
    Yii::$app->response->format = Response::FORMAT_JSON;
    $headers = Yii::$app->response->headers;
    $headers->set('Expires', gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60)));
    Yii::$app->user->enableSession = false;
    Yii::$app->user->loginUrl = null;
}

这仍然给了我

Expires → Thu, 19 Nov 1981 08:52:00 GMT

编辑:我尝试使用下面的 php 方法标头并且它有效。仅当我像这样直接访问标头时,将应用程序类型设置为 JSON 也才有效。

header("Pragma: cache");
header("Content-Type: application/json");
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60)));

我已经尝试将其设置为我的操作。我还考虑过在我的网络配置中设置响应组件过期,但不知道如何输入该值。当我尝试设置 headers 属性时,出现设置只读属性错误。我需要的是为 Android 上的齐射请求的响应设置缓存。如何在我的模块或应用程序上实现此目标?

php yii2
2个回答
0
投票

你错了,应该是:

$headers->set('Expires', gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60)));

0
投票

您需要 afterAction,请参阅 '\yii ase\Module'

<?php
namespace app\api;

use Yii;

/**
 * api module definition class
 */
class Module extends \yii\base\Module
{
    /**
     * {@inheritdoc}
     */
    public $controllerNamespace = 'app\api\controllers';

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();

        // custom initialization code goes here
    }

    public function afterAction($action, $result)
    {
        $result = parent::afterAction($action, $result);

        $response = Yii::$app->response;
        $response->headers->add('Test-Name', 'test-value');

        return $result;
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.